...

View Full Version : Search for first instance



treeleaf20
06-28-2010, 09:31 PM
All,
I have the following text:
<bold>Our Services Include:<endbold>

<bullet>Construction<endbullet><bullet>Landscaping<endbullet>

Then I have the following PHP to replace the contents:


$qrytxt = "Select * from texts where text_id='2'";
$resulttxt = mysql_query($qrytxt);
$resultsettxt = mysql_fetch_array($resulttxt);
$newtxt = $resultsettxt['text'];
$newtxt = str_replace("<endbullet><bullet>", "</li><li>", $newtxt);
$newtxt = str_replace("<bullet>", "<li>", $newtxt);
$newtxt = str_replace("<endbullet>", "</li><br>", $newtxt);
$newtxt = str_replace("<bold>", "<strong>", $newtxt);
$newtxt = str_replace("<endbold>", "</strong>", $newtxt);
echo nl2br($newtxt);


My problem is that if it is the first <bullet> then I want it to replace to <ul><li> instead of just a <li> and also if it's the last <endbullet> then I want it to replace it with </li></ul>

Any ideas on how to do that?

Thanks in advance.

Beagle
06-29-2010, 08:53 AM
First off, let's use arrays:


$replaceThese = array(
"<endbullet><bullet>"
,"<bold>"
,"<endbold>"
,"<endbullet>"
, "<bullet>"
);
$withThese = array(
"</li><li>"
,"<strong>"
, "</strong>"
, "</li><br>"
,"<li>"
);

str_replace($replaceThese, $withThese, $newTxt);


Much nicer. Ok, now, you need to find the first instance of <li> in new text, break the string at that spot, and add the <ul>. You do that with strpos, 2 calls to substr (get the string before the <li> and the string including and after the <li>) and a concatenation ($firstPart."<ul>".$secondPart). Then you repeat this process for the </ul> using strrpos, which searches backwards for the first instance of a string.

Good luck!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum