JBstar
JBstar

Reputation: 47

str_replace with special character scenario

I have a strange scenario any help would be much appreciated, I am trying to put h1 tags on the title, if I use the following code

$phrase  = "*title** Some text goes here.";
$target = ['*', '**'];
$replace   = ["<h1>", "</h1>"];

$newPhrase = str_replace($target, $replace, $phrase);

echo $newPhrase;

The outputted HTML is as follows:

<h1>title</h1>
<h1></h1>
<h1> Some text goes here.</h1>

But if I use the following (same as before but * is replaced with 1 and ** is replaced with 2):

$phrase  = "1title2 Some text goes here.";
$target = ['1', '2'];
$replace   = ["<h1>", "</h1>"];

$newPhrase = str_replace($target, $replace, $phrase);

echo $newPhrase;

It works and I get the output:

 <h1>title</h1>
 Some text goes here. (not as a H1 element)

Can any one explain this please? Why are the * characters treated this way? And can I work around this so I can use them?

Thanks

Upvotes: 1

Views: 48

Answers (1)

user3783243
user3783243

Reputation: 5224

Your ** never matches because the single * matches every occurance. Change the order so you replace the double first.

<?php
$phrase  = "*title** Some text goes here.";
$target = ['**', '*'];
$replace   = ["</h1>", "<h1>"];

$newPhrase = str_replace($target, $replace, $phrase);

echo $newPhrase;

https://3v4l.org/21HZv

You would see the same behavior if you used 1 and 11. Also the HTML you posted is not what the PHP generates I think your browser is auto-correcting that.

Upvotes: 2

Related Questions