仅在标记中用下划线替换空格


Replace spaces with underscore only in tag

data: <product name_here>Product A</product_name here>

我试试这个$replace = preg_replace('/'s+/', '_', $replace);

但它显示不正确,如下所示:<product_name_here>Product_A</product_name_here>

只需在标签名称内用下划线替换空格,无需更改值中的空格

我想要这样:<product_name_here>Product A</product_name_here>

请帮忙。

怎么样?

$before = '<product name_here>Product A</product_name here>';
$after = preg_replace('/(<[^>]*)'s+([^<]*>)/', '$1_$2', $before);
echo $after;

这应该给

<product_name_here>Product A</product_name_here>

''s+ 之前和之后的部分指定您不需要标记对之外的空格,而只需要在开始标记<和结束标记>之间括起来的空格。$1$2 在替换的空格之前和之后替换回字符串。

你能

举一个更好的例子吗?

在我的理解中,你想要这个:

您有:产品 A

您需要:产品 A

这是对的吗?

如果是这种情况,您需要做的就是str_replace('','_',$product)

对不起,我的英语不好。