简体   繁体   中英

PHP preg_match from string

I have this string :

$content = 'Hello <!--blapi[getinfoprix("prix_p1"=>"1-6048df6;image/purchase-small.png"]--> Hello<!--blapi[prix_p1->description]-->';

How can i get the two string <!--*--> in an array[2]?

I've made this :

$pattern = '/<!--blapi\[(.*)\]-->/sU';
preg_match($pattern, $content, $matches);

But I have this result :

array(2) {
  [0]=>
  string(74) "<!--blapi[getinfoprix("prix_p1"=>"1-6048df6;image/purchase-small.png")]-->"
  [1]=>
  string(60) "getinfoprix("prix_p1"=>"1-6048df6;image/purchase-small.png")"
}

I don't understand why it's ignoring the second string <!--blapi[prix_p1->description]--> ...

I've used the flag "U". Maybe there is a better pattern for what I want to do?

EDITION : I expect this result :

Array
(
    [0] => getinfoprix("prix_p1"=>"1-6048df6;image/purchase-small.png"]
    [1] => prix_p1->description
)

This preg_match_all should work:

$content = 'Hello <!--blapi[getinfoprix("prix_p1"=>"1-6048df6;image/purchase-small.png"]--> Hello<!--blapi[prix_p1->description]-->';
if ( preg_match_all('/<!--.*?\[(.*?)\]-->/', $content, $matches) )
   print_r($matches[0]);

OUTPUT

Array
(
    [0] => getinfoprix("prix_p1"=>"1-6048df6;image/purchase-small.png"
    [1] => prix_p1->description
)
$pattern = '~<!--(blapi\[(?:.*?)\])-->~si';

Does this pattern produce the expected results? I understand you want to capture the blapi part too. But not sure...

Changed .*U to .*? and added i for case-insensitive at the end. The inner blapi is a non-capture group and the blapi[...] is now the capture group.

Also avoid wrapping a regex in / as it conflicts with URLs and HTML. Use ~ as it's seldom used and much safer. It's not nice to escape http:// to http:\\/\\/ just because of the wrap character.

You also need preg_match_all as preg_match capture only one match. It's mostly used for match testing, single-match search but not multiple match search.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM