Victor
Victor

Reputation: 11

Find a pattern in a string

I am trying to detect a string inside the following pattern: [url('example')] in order to replace the value.

I thought of using a regex to get the strings inside the squared brackets and then another to get the text inside the parenthesis but I am not sure if that's the best way to do it.

//detect all strings inside brackets
preg_match_all("/\[([^\]]*)\]/", $text, $matches);

//loop though results to get the string inside the parenthesis
preg_match('#\((.*?)\)#', $match, $matches);
    

Upvotes: 0

Views: 514

Answers (1)

The fourth bird
The fourth bird

Reputation: 163352

To match the string between the parenthesis, you might use a single pattern to get a match only:

\[url\(\K[^()]+(?=\)])

The pattern matches:

  • \[url\( Match [url(
  • \K Clear the current match buffer
  • [^()]+ Match 1+ chars other than ( and )
  • (?=\)]) Positive lookahead, assert )] to the right

See a regex demo.

For example

$re = "/\[url\(\K[^()]+(?=\)])/";
$text = "[url('example')]";
if (preg_match($re, $text, $match)) {
    var_dump($match[0]);;
}

Output

string(9) "'example'"

Another option could be using a capture group. You can place the ' inside or outside the group to capture the value:

\[url\(([^()]+)\)]

See another regex demo.

For example

$re = "/\[url\(([^()]+)\)]/";
$text = "[url('example')]";
if (preg_match($re, $text, $match)) {
    var_dump($match[1]);;
}

Output

string(9) "'example'"

Upvotes: 1

Related Questions