user7133318 user7133318 - 1 year ago 98
PHP Question

PHP preg_match with or without letters in front?

Hi I currently have this:

$linkOcc = substr_count($text3, "**link(");
if($linkOcc < '1'){
$text4 = $text3;


for ($i2=0; $i2 < $linkOcc; $i2++) {
preg_match('/(?<=\*\*link)\((.*)\)/', $text3, $match2);
$linkTitle = ($match2[1]);
$linkTitle = str_replace("/","",$linkTitle);

It detects if there is a piece of text in a paragraph that macthes the following:


It then replaces it with something else. This works great if there is a space(s) on both sides of the


But let's say I have the following paragraph:

So then Bob went to this**link(examplesite)**and he found a cool picture.

Then for some reason the code dosnt recognise it as then **link... I am fairly sure it's because there are no spaces on both sides of the **link... So how can I fix this? To detect **link... with AND without spaces on the side of it?

Answer Source

IF you only want to match the text between the parenthesis:

**link(this text)**

Then your regular expression needs to be be:


You are just simply capturing any text -> (.*)
Inside the parenthesis -> \( \)

To test the regular expression you can go here: and test it with or without spaces after or before **link(some text)**

IMPORTANT NOTE: Since you only have one capturing group, the match is going to be on the first element of the match array: matches[0]

In your case if you want the matched content, you need to use $match2[0] instead of $match2[1]

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download