我是stackoverflow 的新手
所以我有一个html文件,里面有很多<span style="display:none;">some text</span>
他们的数量超过100或200。我想用随机字符串替换跨度的内部文本
但我遇到了两个问题,第一个问题是我找不到正确的正则表达式模式来使用内联style="display:none"
查找span
但我可以用/<span (.*?)>(.*?)</span>/
获得所有跨度的文本。第二个问题来了。我使用php,这是我的代码
preg_match_all('/<span (.*?)>(.*?)</span>/', $file, $matches);
foreach ($matches as $value) {
$string = str_replace($value, RandomString(), $file);
}
因此,它更改了所有跨度的内部文本,但同时,RandomString()
是一个生成随机字符串的函数,在str_replace
之后,它返回更改后的字符串,但所有跨度的值都是相同的,因为我的随机字符串生成器只工作一次,str_replace()
替换所有找到的匹配
我想过递归
function rec($string)
{
preg_match('/<span (.*?)>(.*?)</span>/', $string, $matches);
if (!$matches) {
return $string;
}
foreach ($matches as $value) {
$string = str_replace($value,RandomString(), $string);
rec($string);
}
}
但它返回500个错误。。。
那么,我如何一步一步地替换找到的匹配项呢?
示例
<span>not to change text</span>
<span style="display:none">change text</span>
<span style="display:none">change text</span>
我希望它像
<span>not to change text</span>
<span style="display:none">some random string</span>
<span style="display:none">other ddifferent random string</span>
Regex是强制性的
最好使用类似DOM 的东西
但是您写的regex是强制性的,所以这里有一个工作示例:
preg_match_all('/<span .*?display:none.*?>(.*?)</span>/', $string, $matches);
foreach($matches[1] as $match) {
$string = preg_replace('/>' . $match . '</', '>' . rand() . '<', $string, 1);
}