user849137
user849137

Reputation:

issues with preg_match PHP

I have a string:

$str="(94896)content is here(/94896)(94897)content is here(/94897)(94898)content is here(/94898)(94899)content is here(/94899)";

the (number) and (/number) act as tags to take certain content out of the string.

and I have a preg_match to take the content out:

if(preg_match('/(94896)\"(.*)\"(\/94896)/',$str,$c)) {echo "I found the content, its:".$co[1];} 

Now for some reason, it doesn't find a match in the string ($str), though its clearly there....

Any ideas on what im doing wrong here?

Upvotes: 0

Views: 81

Answers (3)

Francis Avila
Francis Avila

Reputation: 31621

To match all content:

$str="(94896)content is here(/94896)(94897)content is here(/94897)(94898)content is here(/94898)(94899)content is here(/94899)";

$re = '/\((\d+)\)(.*)\(\/\1\)/';
preg_match_all($re, $str, $matches,PREG_SET_ORDER);
var_dump($matches);

Number will be in $matches[*][1], content in $matches[*][2].

Upvotes: 0

Adonais
Adonais

Reputation: 1292

Parentheses are used in a regex to denote subpatterns. If you want to search these characters in a string, you must escape them:

preg_match('/\(94896\)(.*)\(\/94896\)/',$str,$c)

If the pattern is found:

echo "I found the content, its:".$c[0];

Oh, and as Karl Nicoll says, why are the quotations in your pattern?

Upvotes: 1

Karl Nicoll
Karl Nicoll

Reputation: 16419

You need to take the double-quotes out of your regex string, since they don't appear in $str, but are expected by the regex.

'/(94896)\"(.*)\"(\/94896)/'
//       ^^    ^^
//        These aren't in the string.

EDIT: I think you'll also need to escape your brackets, since they will be getting read as grouping operators, not actual brackets.

Your expression should be:

'/\(94896\)(.*)\(\/94896\)/'

Upvotes: 2

Related Questions