简体   繁体   English

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

[英]Replace spaces with underscore only in tag

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

I try this $replace = preg_replace('/\\s+/', '_', $replace); 我尝试这个$replace = preg_replace('/\\s+/', '_', $replace);

but it show incorrect like this : <product_name_here>Product_A</product_name_here> 但它显示不正确,如下所示: <product_name_here>Product_A</product_name_here>

Just only replace space with underscore only inside tag name , no need to change space in value 仅在标记名称内仅用下划线替换空格,无需更改值的空间

I want like this : <product_name_here>Product A</product_name_here> 我想要这样: <product_name_here>Product A</product_name_here>

Please help. 请帮忙。

How about? 怎么样?

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

This should give 这应该给

<product_name_here>Product A</product_name_here>

The parts before and after \\s+ specify that you don't want the spaces outside of a tag pairing but just the ones who are enclosed between an opening tag < and a closing tag > . \\ s +之前和之后的部分指定您不希望标签配对之外的空格,而只需要包含在开始标签<和结束标签>之间的空格。 The $1 and $2 substitute back in the strings before and after the replaced whitespace. $1$2在替换的空格前后都替换为字符串。

Can you give a better example? 你能举一个更好的例子吗?

In my understanding you want this: 以我的理解,您需要这样做:

You have: Product A 您具有:产品A

You want: Product A 您要:产品A

Is that correct? 那是对的吗?

If that's the case all you need to do is str_replace(' ','_',$product) 如果是这种情况,您要做的就是str_replace('','_',$ product)

Sorry for my bad english. 对不起,我的英语不好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM