View Full Version : Search for first instance

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


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.

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

$replaceThese = array(
, "<bullet>"
$withThese = array(
, "</strong>"
, "</li><br>"

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!