开发者

Multiline regex issue in PHP

开发者 https://www.devze.com 2023-01-10 21:32 出处:网络
Consider the code below, why it is not working? <?php $str = \" <h4> title </h4> \"; $result = preg_match_all (\'/<h4>([\\d\\D])<\\/h4>/mi\', $str, $matches);

Consider the code below, why it is not working?

<?php

$str = "
<h4>
   title
</h4>
";

$result = preg_match_all ('/<h4>([\d\D])<\/h4>/mi', $str, $matches);
开发者_运维技巧var_dump($matches);


You probably meant

$str = "
<h4>
   title
</h4>
";

$result = preg_match_all ('/<h4>(.+?)<\/h4>/si', $str, $matches);
var_dump($matches);

The regex you applied, '/<h4>([\d\D])<\/h4>/mi', means "Match an opening h4, one character that's either a digit or not a digit, and a closing h4." But you have plenty of characters to match, so you need to specify a quantifier ("more than one", +). Update: you need a non-greedy quantifier, +?, if you have more than one h4 (very likely!) And the class [\d\D] can be reduced to "any character", .. One more point: you need to use /s instead of /m to get the behaviour you want.

This will probably include the newlines in your match!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号