DroidStack
DroidStack

Reputation: 129

Replace spaces with underscore only in tag

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

I try this $replace = preg_replace('/\s+/', '_', $replace);

but it show incorrect like this : <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>

Please help.

Upvotes: 1

Views: 502

Answers (2)

Daniel82
Daniel82

Reputation: 101

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 >. The $1 and $2 substitute back in the strings before and after the replaced whitespace.

Upvotes: 1

Paulo Lima
Paulo Lima

Reputation: 76

Can you give a better example?

In my understanding you want this:

You have: Product A

You want: Product A

Is that correct?

If that's the case all you need to do is str_replace(' ','_',$product)

Sorry for my bad english.

Upvotes: 0

Related Questions