Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP str_replace with wild card?

Tags:

php

I know how to use str_replace for simple tasks, like this...

$Header = str_replace('<h2>Animals</h2>', '<h3>Animals</h3>', $Header);

But imagine an article stored in a database that includes the following headers:

<h3>Animals</h3>
<h3>Plants</h3>

And you want to change them to this:

<h3><span class="One">Animals</span></h3>
<h3><span class="One">Plants</span></h3>

Is there a way to turn the value between the tags (e.g. Animals, Plants, Minerals, etc.) into a wild card, something like this?:

$Title = str_replace('<h3>*</h3>', '<h3><span style="One">*</span></h3>', $Title);

Or I should ask "What's the best way?" It looks like there are ways to do it, but I'd like to try and find a simple PHP solution before I start wrestling with regular expressions.

like image 791
David Blomstrom Avatar asked Feb 07 '15 02:02

David Blomstrom


1 Answers

You can use the str_replace() technique that has been suggested in the primary comments, but I believe preg_replace() using regular expressions is the best practice for wildcard replacements.

<?php
$str = <<<EOD

<h3>Animals</h3>
<h3>Plants</h3>

EOD;

$str = preg_replace('/<h3>(.*?)<\/h3>/', '<h3><span class="One">$1</span></h3>', $str);

echo $str;
like image 88
Samuel Cook Avatar answered Sep 30 '22 12:09

Samuel Cook