1

I have the following string:

"Canal Capital(Canal Capital) Felipe Cano - Recursos Humanos - [email protected] - (Canal Capital) Andres Zapata - Tecnologías de la Información - [email protected] - 3212032851(Canal Capital) Miguel Cabo - Canal Capital - [email protected] - 457 83 00 Ext. 5227 301 734 07 56"

I want to be able to remove a repeating pattern inside the string, so if the pattern is (Canal Capital), I should end up with:

"Canal Capital Felipe Cano - Recursos Humanos - [email protected] - Andres Zapata - Tecnologías de la Información - [email protected] - 3212032851 Miguel Cabo - Canal Capital - [email protected] - 457 83 00 Ext. 5227 301 734 07 56"

So far I've tried this (It works if the pattern repeats itself only once):

$cadena = preg_replace("/\(.*\)/", "", $cadena);

But I get just the first "Canal Capital" part. Can I achieve my goal with regex ? Maybe there's a better way to accomplish this that I don't know about. Thanks.

2 Answers 2

1

You can use the following pattern as

/(?<=[\w-\s\S])(\(.*?\))(?=[\w\s\S])/
  • (?<=[\w-\s\S]) Positive Lookbehind - [\w-\s\S] match a single character present in the list below
  • \( matches the character ( literally
  • .*? matches any character (except newline)
  • \) matches the character ) literally
  • (?=[\w\s\S]) Positive Lookahead - [\w\s\S] match a single character present in the list below

So the code looks like as

$res = preg_replace('/(?<=[\w-\s\S])(\(.*?\))(?=[\w\s\S])/', '', 'Canal Capital(Canal Capital) Felipe Cano - Recursos Humanos - [email protected] - (Canal Capital) Andres Zapata - Tecnologías de la Información - [email protected] - 3212032851(Canal Capital) Miguel Cabo - Canal Capital - [email protected] - 457 83 00 Ext. 5227 301 734 07 56');
echo $res;

Or you can simply use this as

/(\(.*?\))/

Demo

Regex

Sign up to request clarification or add additional context in comments.

Comments

0

You are almost close, you are just missing the ? quantifier which makes the greedy matcher, non-greedy (lazy).

Try like this:

(\(.*?\))

which results:

Canal Capital Felipe Cano - Recursos Humanos - [email protected] - Andres Zapata - Tecnologías de la Información - [email protected] - 3212032851 Miguel Cabo - Canal Capital - [email protected] - 457 83 00 Ext. 5227 301 734 07 56

Demo

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.