...

View Full Version : replace <p>...</p> with <span>...</span>



shajiuddin
01-15-2012, 12:52 PM
Hi,

From db variable am getting content like this "<p>This is the description</p>"

I need to replace it to "<span>This is the description</span>"

I used "str_replace()" but this function is for 1 variable and i have to use 2 variable

1st is for <p> and 2nd for </p>

Please help


Regards

BluePanther
01-15-2012, 01:41 PM
str_replace can take array parameters:
php.net/manual/en/function.str-replace.php

Although you might be better with a regular expression, str_replacing with array parameters will work.

Kekke
01-15-2012, 02:42 PM
You can just do it twice in a row




$string = "<p>Hello</p>";
$string = str_replace("<p>", "<span>", $string);
$string = str_replace("</p>", "</span>", $string);
echo $string;

BluePanther
01-15-2012, 03:12 PM
You can just do it twice in a row




$string = "<p>Hello</p>";
$string = str_replace("<p>", "<span>", $string);
$string = str_replace("</p>", "</span>", $string);
echo $string;

Or, use arrays like I said :)


$string = '<p>hello</p>';
$string = str_replace(array('<p>','</p>'),array('<span>','</span>'),$string);

shajiuddin
01-16-2012, 08:30 AM
Hi,

BluePanther, you are right but the situation is there is more then lines are retrieving like this

i-e:
<p>Hello 1</p>
<p>Hello 2</p>
<p>Hello 3</p>

I need to change for first line only like this

i-e
<span>Hello 1</span>
<p>Hello 2</p>
<p>Hello 3</p>


Please help


Regards

BluePanther
01-16-2012, 09:46 AM
Hi,

BluePanther, you are right but the situation is there is more then lines are retrieving like this

i-e:
<p>Hello 1</p>
<p>Hello 2</p>
<p>Hello 3</p>

I need to change for first line only like this

i-e
<span>Hello 1</span>
<p>Hello 2</p>
<p>Hello 3</p>


Please help


Regards

Is this first line always going to have the same content inside the tags?

shajiuddin
01-16-2012, 10:03 AM
Hi,

content will be same always but the tags will remain same.


Regards

BluePanther
01-16-2012, 10:10 AM
Hi,

content will be same always but the tags will remain same.


Regards

If the content remains the same in the first tag, but the content in the other tags is different, why not just do this?



$string = str_replace('<p>Content</p>','<span>Content</span>',$string);

shajiuddin
01-16-2012, 10:14 AM
Sorry I had mistake in my wordings

content will not be same always but the tags will remain same.

BluePanther
01-16-2012, 01:04 PM
Ah, ok. In this case, a regular expression is probably your best bet:


$string = '<p>one</p><p>two</p><p>three</p>';
$string = preg_replace('/\<p>(.*?)\<\/p>/i','<span>${1}</span>',$string,1);
// $string is now <span>one</span><p>two</p><p>three</p>

The preg_replace function takes a match parameter, a replacement paramenter, the subject, then an optional replacement limit and count. We supply the limit as 1, meaning it will only replace the first match.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum