0

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

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.