0

I'm trying to change some parts of a string. I used preg_replace() function for this stuation but I couldn't succeed.

Here is an example.

$str = "Suspendisse rutrum rhoncus leo vitae vehicula. <span class="sdsad"> Nunc nec dapibus nisi.</span> Donec facilisis mauris sapien, eget blandit enim  dignissim auctor. <span style="text-decoration: underline;" class="sadsad">Nullam a porta orci.</span>";

I need to get parts begin with "<span" and after all till ">" charecter and turn it <p> or something else.

$str = preg_replace('/<span.*>/', '<p>', $str);

I'm trying to solve this like that but it returns the same value.

What do I need to do this ?

Thank you..

2 Answers 2

1

This Regex will do the trick for you.

$str = 'Suspendisse rutrum rhoncus leo </span> vitae vehicula. <span class="sdsad"> Nunc nec dapibus nisi.</span> Donec facilisis mauris sapien, eget blandit enim  dignissim auctor. <span style="text-decoration: underline;" class="sadsad">Nullam a porta orci.</span>';
$str_replaced = preg_replace('/<(\/{0,1})span[^>]*>/','<$1p>',$str);
echo $str_replaced;

It will optionally put the trailing slash into the tags so you will only need one call.

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

2 Comments

Way to complicated ?!
Not at all. This way you will have <span clas="xyz"> and </span> replaced with <p> and </p> in one go.
0

You forgot the capturing group here ()

$str = preg_replace('/<span(.*)>/', '<p>', $str);

More info here: http://www.regular-expressions.info/brackets.html

3 Comments

unfortunately I'm getting the same result.
@brk: I tested this on infoheap.com/tool/php-preg_replace-sandbox - works perfectly. Maybe some kind of cache?
yes it's working correctly in that link. i'm trying tıo find some reasons.

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.