I am trying to replace the occurrence of li
tag with a
tag but I also replace the other li
s used in the string.
for example I have this:
<li id="item" class="list-item" href="#">Item</li>
but I want to replace the li
tags without the list-item
class name replaced.
if I do :
$f = array( '><a', 'li' );
$r = array( '', 'a' );
// output the menu
echo str_replace( $f, $r, $menu );
then the class name list-item
becomes ast-item
where li
is replaced with a
.
How can I just replace the li tag and not all the instance of li?
Try something like this:
$string = '<li id="item" class="list-item" href="#">Item</li>';
$string = preg_replace("/<li\s(.+?)>(.+?)<\/li>/is", "<a $1>$2</a>", $string);
echo($string);
try this
$input_lines = '<li id="item" class="list-item" href="#">Item</li>';
preg_replace("/\<(\/?)li([^\>]*)\>/", "<$1a$2>", $input_lines);
You could try making your search params a bit more accurate to avoid that problem. Example:
$menu = "<li id=\"item\" class=\"list-item\" href=\"#\">Item</li>";
$f = array( '<li', '</li>' );
$r = array( '<a', '</a>' );
// output the menu
$x = str_replace( $f, $r, $menu );
Generally speaking, you should avoid parsing HTML with Regexs.
If you want to do exactly as the question states. First and last li
Then you can use strpos to find the first.
And use strrpos to find the last.
This is more a demonstration of the exact answer to the question rather than a good way.
As I linked to in the comments above str_replace is better.
$s = '<url id="item" class="list-item" href="#">Item</url>';
$find = "url";
$lenght = strlen($find);
$pos1 = strpos($s, $find);
$pos2 = strrpos($s, $find);
Echo substr($s,0,$pos1) . "a" . Substr($s,$pos1+$lenght,$pos2-$lenght-1) . "a" . Substr($s,$pos2+$lenght);
Note that I add or subtract from position depending on if I want to keep or delete the words.
https://3v4l.org/J1Na0
Updated with a more universal solution.