Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何对未知值使用preg_replace_回调?_Php_Regex - Fatal编程技术网

Php 如何对未知值使用preg_replace_回调?

Php 如何对未知值使用preg_replace_回调?,php,regex,Php,Regex,今天我得到了一些很大的帮助,开始理解preg_replace_回调的已知值。但现在我想处理未知值 $string = '<p id="keepthis"> text</p><div id="foo">text</div><div id="bar">more text</div><a id="red"href="page6.php">Page 6</a><a id="green"href="pag

今天我得到了一些很大的帮助,开始理解preg_replace_回调的已知值。但现在我想处理未知值

$string = '<p id="keepthis"> text</p><div id="foo">text</div><div id="bar">more text</div><a id="red"href="page6.php">Page 6</a><a id="green"href="page7.php">Page 7</a>';
$string='

text

textmore text';
有了这个字符串,我将如何使用preg_replace_回调来删除div和a标记中的所有id,但保持p标记的id不变

所以从我的绳子

<p id="keepthis"> text</p>
<div id="foo">text</div>
<div id="bar">more text</div>
<a id="red"href="page6.php">Page 6</a>
<a id="green"href="page7.php">Page 7</a>

文本

文本 更多文本

文本

文本 更多文本
对于您的示例,以下内容应该可以使用:

$result = preg_replace('/(<(a|div)[^>]*\s+)id="[^"]*"\s*/', '\1', $string);
$result=preg_replace('/(]*\s+)id=“[^”]*“\s*/”,'\1',$string);

尽管通常情况下,您最好避免使用正则表达式解析HTML,而是使用适当的解析器(例如,将HTML加载到DOMDocument并使用方法,如中)。这样,您可以更好地处理标记和格式错误的HTML。

不需要回调

$string = preg_replace('/(?<=<div|<a)( *id="[^"]+")/', ' ', $string);

“我将如何使用preg_replace_回调到[…]”-理想情况下,…因此,在这种情况下,我应该坚持使用preg_replace或str_replace?如果您不知道$string的未来,最好使用HTML解析器,因为我已经厌倦了发布大量的答案,所以我已经添加了一些注释。使用
preg_replace()
使用
x
修饰符并删除
g
修饰符。一些建议:1)如果你不确定你得到的输入或你的正则表达式技能不好,那么就使用2)这个问题得到了相当多的赞成票,我不明白为什么,但你真的应该发布你的尝试3)或访问!感谢你给出了bot的示例H
$string = preg_replace('/(?<=<div|<a)( *id="[^"]+")/', ' ', $string);
echo preg_replace_callback(
    '/(?<=<div|<a)( *id="[^"]+")/',
    function ($match)
    {
        return " ";
    },
    $string
 );