PHP的str_replace与通配符? [英] PHP str_replace with wild card?

查看:146
本文介绍了PHP的str_replace与通配符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何将str_replace用于诸如此类的简单任务...

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>

您想将它们更改为此:

<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);

或者我应该问:最好的方法是什么?"看来有很多方法可以做到,但是我想尝试着找到一个简单的PHP解决方案,然后再开始使用正则表达式.

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.

推荐答案

您可以使用主要注释中建议的str_replace()技术,但我相信

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;

这篇关于PHP的str_replace与通配符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆