简体   繁体   中英

php - use of preg_match or preg_match_all

<font size="+1"><font size="+2" color="green"><b>1.</b> 
</font><b>If no head injury is too trivial to be neglected, then:</b></font>

In PHP using preg_match or preg_match_all I want to retrieve the text "If no head injury is too trivial to be neglected, then:"

How can I do this?

Code:

<?php

$str = '<font size="+1"><font size="+2" color="green"><b>1.</b></font><b>If no head injury is too trivial to be neglected, then:</b></font>';
$pattern = "/font><b>(.+)<\/b>/";
preg_match($pattern,$str,$matches);

echo $matches[1];

?>

Output:

If no head injury is too trivial to be neglected, then:

I am not sure, under what conditiones you select the string to capture, why gets 1. not captured, but your 2. string does? As long, as you do not explain that I can only guess, so as an expression:

/<\w+(?:\s+\w+=(?:(?:"[^"]*")|(?:'[^']*')))*\s*>([^<]+)</\w+>/g

will match all html tags, that only contain a text node (wich should be case for xhtml, since <p>text<br /></p> would not be wellformed...).

so <p>text</p><br>text2</br> will be matched and as a result the text will be in capturegroup 1.

<\w+(?:\s+\w+=(?:(?:"[^"]*")|(?:'[^']*')))*\s*> will capture every opening xhtml tag

([^<]+) will catch all cahrs exept from < and put it in the capturegroup

</\w+> finally catches the closing tag...

the g is the global flag so that the expression can catch multiple results...

Good luck with this, if you need something different please be a little more precise...

The pattern will be something like this:

/<\s*b\s*>(.+)<\s*\/b\s*>/

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