0

If I have the following string for example:

"Value1 *|VALUE_2|* Value3"

I want to be able to remove any substrings from within the string that begins with the chracters | and end in |. I will not know what will be between these characters but this is irrelevant as I want to remove whatever is between them.

Basically, I am just unsure of what pattern to use in the code below.

preg_replace("*|PATTERN|*", "", $str);
0

3 Answers 3

1

| is a special character that needs to be escaped in regex:

preg_replace('/\|[^|]+\|/', '', $str);
Sign up to request clarification or add additional context in comments.

Comments

0
preg_replace('/|[^|]+|/', '', $str);

This should do the trick.

Comments

0
preg_replace("/\|.*\|/U", "", $str);

I think this should do the trick..

The /U makes the pattern ungreedy so that in Value1 |VALUE_2| Value3|test the match will be |VALUE_2| instead o |VALUE_2| Value3|

If you only want the contents between the |'s removed, you can do:

preg_replace("/\|.*\|/U", "||", $str);

There are other ways, but this would be the most easy one imho.

3 Comments

Thanks for the detailed reply. When I posted initially, the * char got removed from the sample so the example should be "Value1 * |VALUE_2| * Value3" and not "Value1 |VALUE_2| Value3".
I don't think that will make a difference .. .* will match anything between the |'s
@M42's answer was correct in stating that | needs to be escaped. Adjusted code accordingly.

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.