Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore some words inside string when using preg_replace

What i'm trying to do is

$var = "[h1]This is Just a text, [h1]and this inside it[/h1] This just example[/h1]";
$output = preg_replace("/\[h1\](.*?)\[\/h1]/", "<h1>$1</h1>", $var);
echo $output;

Here i want to ignore first [/h1] to make the result right, How can i achieve it? Did there is anyway to just get first and last tags?

I don't know what i should do or try, i'm not good enough to try in it,

Edited

The output is

<h1>This is Just a text, [h1]and this inside it</h1> This just example[/h1]

but i expected to get

<h1>This is Just a text, <h1>and this inside it</h1> This just example</h1>
like image 413
Iris Tako Avatar asked Mar 14 '26 17:03

Iris Tako


1 Answers

You can achieve your desired output without using regex, if you simply want to replace the strings [h1] for <h1> etc.

<?php
$var = "[h1]This is Just a text, [h1]and this inside it[/h1] This just example[/h1]";

echo str_replace(['[h1]', '[/h1]'], ['<h1>', '</h1>'], $var);

Result:

<h1>This is Just a text, <h1>and this inside it</h1> This just example</h1>

https://3v4l.org/q9a41

like image 170
Lawrence Cherone Avatar answered Mar 17 '26 05:03

Lawrence Cherone



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!