1

I need to create a function to replace

[li]text[/li]

into

 <li>text</li>

This is the regex Im testing but nothing

 $string="[li]A[/li] [li]B[/li] [li]C[/li] [li]D[/li]";

 $pattern = "/[li](.*?)[\/li]/s";
$string = preg_replace($pattern, "$1", $string);

 echo $string; //but returns: []A[/] []B[/] []C[/] []D[/]

but nothing, what Im doing wrong?

3
  • 1
    Square brackets in regexp are special. You need to escape those too. Commented May 7, 2020 at 2:05
  • scaping and using this new regex puts everything within a single li /\[li\](.*?)\[\/li\]/s Commented May 7, 2020 at 2:14
  • Should [li]text without [/li] be altered? Can we assume that if [/li] is present it will be preceded by [li]? Is it just [li], or, could it be, say, [a] and [/a]? Commented May 7, 2020 at 3:19

2 Answers 2

1

you should insert the < li > in the replace command

$string="[li]A[/li] [li]B[/li] [li]C[/li] [li]D[/li]";
$pattern = "/\[li\](.*?)\[\/li\]/s";
$string = preg_replace($pattern, "<li>$1</li>", $string);
echo "<pre>";
echo $string;
echo "</pre>";
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. what if within one or several li are there linebreaks? thank you
you could do another command at beggining of code to replace \n like $string = preg_replace("/(\n)/", "", $string);
Newlines shouldn't affect it. They're just characters.
0
$string="[li]A[/li] [li]B[/li] [li]C[/li] [li]D[/li]";
$string = preg_replace('/\[(.*?)\](.*?)\[\/(.*?)\]/', '<$1>$2</$3>', $string);
echo $string;

Result:

<li>A</li> <li>B</li> <li>C</li> <li>D</li>

Comments

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.