PHP正则方面的问题

$str ='<strong><span style="font-size:14px;" id="drug contraindication">drug contraindication</span></strong>aaaaa<strong><span style="font-size:14px;" id="to sleep">to sleep</span></strong>';

preg_replace正则将html属性ID中的空格替换成_(下划线)如下面这样
<strong><span style="font-size:14px;" id="drug_contraindication">drug contraindication</span></strong>aaaaa<strong><span style="font-size:14px;" id="to_sleep">to sleep</span></strong>

参考下js的

$str ='<strong><span style="font-size:14px;" id="drug contraindication">drug contraindication</span></strong>aaaaa<strong><span style="font-size:14px;" id="to sleep">to sleep</span></strong>';
 
$str.replace(/id="[^"]+/g,function(p1,p2){
    return p1.replace(/ /g,'_')
})

你可以使用 preg_replace 函数结合正则表达式来替换 HTML 属性中的空格为下划线。下面是一个示例代码:

$str = '<strong><span style="font-size:14px;" id="drug contraindication">drug contraindication</span></strong>aaaaa<strong><span style="font-size:14px;" id="to sleep">to sleep</span></strong>';

$result = preg_replace('/id="([^"]*)"/', 'id="$1"', $str);
$result = preg_replace('/ /', '_', $result);

echo $result;

在上述代码中,我们首先使用正则表达式 /id="([^"]*)"/,匹配所有的 id 属性,并使用捕获组 $1 来保留属性值。然后,我们通过替换为 id="$1",将属性中的空格移除。

接下来,我们再次使用正则表达式 / /,匹配所有的空格,并将其替换为下划线 _

最后,我们将替换后的结果打印出来,即可得到你所期望的输出。

请注意,使用正则表达式来处理 HTML 是一个简单的示例,对于更复杂的 HTML 结构,可能需要更复杂的正则表达式或者考虑使用 HTML 解析器进行处理。

希望这个示例对你有帮助。如有其他疑问,请随时追问。