0

Lets say I have the following string:

"**link(http://google.com)*{Google}**"

And I want to use preg_match to find the EXACT text **link(http://google.com) but the text inside the brackets changes all the time. I used to use:

preg_match('#\((.*?)\)#', $text3, $match2);

Which would get what is inside the brackets which is good but if I had: *hwh(http://google.com)** it would get whats inside of that. So how can i get whats inside the brackets if, in front of the brackets has **link?

JonathanStevens
  • 472
  • 3
  • 9

3 Answers3

0

Here

preg_match("/\*\*link\((\D+)\)/",$text,$match);
0

~(?:\*\*link\(([^\)]+)\))~ will match contents in the brackets for all inputs that look like **link(URL) but do not contain extra ) inside URLs. See the example on Regexr: http://regexr.com/3en33 . The whole example:

$text = '"**link(http://google.com)*{Google}**"
**link(arduino.cc)*{official Arduino site}';
$regex = '~(?:\*\*link\((?<url>[^)]+))~';
preg_match_all($regex, $text, $matches);

var_dump($regex, $matches['url']);
Tomasz Kowalczyk
  • 10,472
  • 6
  • 52
  • 68
0

Use a lookbehind operator ?<= (?<=\*\*link)\((.*)\) gives you what's inside braces if the text behind is **link

Update:

Here's a PHP example

Here's a regex example

Tala
  • 909
  • 10
  • 29
  • it says Unknown modifier '\' – user7133318 Nov 20 '16 at 19:30
  • If you are yousing double quotes for string literal, use `\\` instead of `\`. In double quotes `\` is the escape character. – Tala Nov 20 '16 at 19:34
  • i misunderstand, this is what i have what is wrong with it, preg_match("(?<=\*\*link)\((.*)\)", $text3, $match2); – user7133318 Nov 20 '16 at 19:36
  • I have updated the answer to include working examples of PHP and standalone regex. see the difference in methods resulting to `$match1` and `$match2` are the string literal definition (double vs single quote). – Tala Nov 20 '16 at 19:57