我有一个字符串,它是这样的:
$str="
<code>
lol
test
</code>
test";
我想修剪标签中的文本,这样我就可以得到这个:
$str="
<code>lol
test</code>
test";
有没有办法把它分成3个数组,然后在中间的文本上做一个简单的trim()?
非常感谢
应该这样做。它所做的是查找后面跟着任意数量空格的<tag>
并进行修剪,直到找到另一个非空格字符。然后,它在关闭</tag>
之前删除任意数量的空格。
preg_replace(array(
'/(<[a-zA-Z]+>)[[:space:]]*([^[:space:]])/m',
'/[[:space:]]*(<'/[a-zA-Z]+>)/m',
), array(
''1'2',
''1',
), $str);
在行动中看到它:http://codepad.org/Stmd32QL
编辑
这将只查找<code>
标记。
preg_replace(array(
'/(<code>)[[:space:]]*([^[:space:]])/mi',
'/[[:space:]]*(<'/code>)/mi',
), array(
''1'2',
''1',
), $str);
Regex不是正确的解决方案,如果您想获得最佳结果,应该使用html解析库。但是,如果您对使用regex解析html的问题感到满意;这应该做到:
<?php
$string = "
<code>
lol
test
</code>
test";
$pattern = '/(<([a-z]+)>)'s*(.+)'s*(<'/'2>)/ms';
$new_string = preg_replace_callback($pattern, function ($m) {
return $m[1].trim($m[3]).$m[4];
}, $string);
var_dump($new_string);
结果:
$ php test.php
string(35) "
<code>lol
test</code>
test"
请注意,这里的示例简化了html标记模式,如果需要支持<coDe style="color: red;">