Home  >  Article  >  Backend Development  >  php正则表达式怎么匹配首尾空白的情况?

php正则表达式怎么匹配首尾空白的情况?

WBOY
WBOYOriginal
2016-06-06 20:28:181385browse

比如:

<code><ul>
    <li> - 中华人民共和国 - </li>
</ul>
</code>

要提取出“中华人民共和国”,正则表达式应该怎么写?

回复内容:

比如:

<code><ul>
    <li> - 中华人民共和国 - </li>
</ul>
</code>

要提取出“中华人民共和国”,正则表达式应该怎么写?

利用提取中文字符的思路:

<code class="php"><?php $str = '<ul>
    <li> - 中华人民共和国 - </li>
';

preg_match('/<ul>\s*<li>[^\x{4e00}-\x{9fff}]*([\x{4e00}-\x{9fff}]*)[^\x{4e00}-\x{9fff}]*\s*/u', $str, $arr);
print_r($arr);

// 结果
/*
Array
(
    [0] => <ul>
    <li> - 中华人民共和国 - </li>
</ul>
    [1] => 中华人民共和国
)
*/</li>
</ul></code>

可以先使用trim(),然后再正则么?

能不用正则的坚决不用正则。

PHP直接解析DOM然后+trim

trim的第二个参数很方便

就算一定要用正则也要让正则干最少的工作。

trim(' - ')

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn