Varun kumar
Varun kumar

Reputation: 3039

Strip leading and trailing whitespaces within a string matched using regex in php

I have a html string

$html = <p>I'm a para</p><b>  I'm bold  </b>

Now I can replace the bold tags with wiki markup(*) using php regex as:

$html = preg_replace('/<b>(.*?)<\/b>/', '*\1*', $html); 

Apart from this I also want the leading and trailing whitespaces in the bold tag removed in the same php's preg_replace function.

Can anyone help me on how to do this?

Thanks in advance,

Varun

Upvotes: 0

Views: 508

Answers (3)

Alma Do
Alma Do

Reputation: 37365

Use \s symbol for that (\s* means that there could be 0 or more occurrences):

$html = preg_replace('/\<b\>\s*(.*?)\s*\<\/b\>/i', '*\1*', $html);

-I also suggest to use i modifier since html tags are case insensitive. And, finally, symbols < and > should be escaped for more safety (they are part of some regex construsts. Your regex will work without escaping them, but it's a good habit to escape them so be sure to avoid errors with that)

(edit): it seems I've misunderstood 'trailing/leading' sense.

Upvotes: 1

hwnd
hwnd

Reputation: 70732

Apart from this I also want the leading and trailing whitespaces in the bold tag removed

Easy enough this will do it just fine.

$html = preg_replace('/<b>\s+(.*?)\s+<\/b>/', '*\1*', $html);

See the demo

Upvotes: 1

Jerry
Jerry

Reputation: 71578

Try using:

$html = preg_replace('~<b>\s*(.*?)\s*</b>\s*~i', '*\1*', $html);

\s in between the tags and the string to keep will strip away the spaces to trim. The i flag just for case insensitivity and I used ~ as delimiters so you don't have to escape forward slashes.

Upvotes: 1

Related Questions