1

This is my string:

Versandkosten (Versand - Kosten)(innerhalb Deutschlands)

I want to replace the first part in parentheses, so after replacing it should look like that:

Versandkosten (innerhalb Deutschlands)

The first part is not always the same, but its always this pattern: (something - something).

This is what I tried, but it always replaces everything:

$title = 'Versandkosten (Versand - Kosten)(innerhalb Deutschlands)';
$title = preg_replace('/\(.+[-].+\)/', '', $title);

Thanks for helping!

4
  • actually, your current regex matches ( Versand - Kosten)(innerhalb Deutschlands ) . Commented Jun 30, 2014 at 8:40
  • Yeah, I know ;)... but how do I make it match only the first part? Commented Jun 30, 2014 at 8:40
  • try replacing your dots with [a-zA-Z ]. Complete with any sign that might be contained in the name, or use \w. The important part is that it doesn't contain ( or ). As dots means "any character" in regex, ( is considered valid and is captured in your regex Commented Jun 30, 2014 at 8:42
  • What if input is Versandkosten (Versand)(innerhalb Deutschlands) what output do you expect? Commented Jun 30, 2014 at 8:42

3 Answers 3

3

Use this:

$replaced = preg_replace('~\([^)-]*-[^)]*\)~', '', $yourstring);

In the demo, look at the substitutions at the bottom.

Explanation

  • `( matches the opening parenthesis
  • [^)-]* matches any chars that are neither a ) nor a -
  • - matches the hyphen
  • [^)]* matches any chars that are not a )
  • `) matches the closing parenthesis
  • We replace with the empty string
Sign up to request clarification or add additional context in comments.

1 Comment

FYI, added full explanation. :)
0

You can use:

$re = "/^([^()]*)\([^)]*\)(.*)$/m"; 

$result = preg_replace($re, '\1\2', $input);

Working Demo

Comments

0

You could try this regex if you want to remove the first () paranthesis.

(^.*?)(\([^\)]*\))

Your code would be,

<?php
$string = 'Versandkosten (Versand - Kosten)(innerhalb Deutschlands)';
$pattern = "~(^.*?)(\([^\)]*\))~";
$replacement = "$1";
echo preg_replace($pattern, $replacement, $string);
?> //=> Versandkosten (innerhalb Deutschlands)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.