简体   繁体   中英

Multiline regex issue in PHP

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!

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