PHP使用str_replace和preg_replace [英] PHP Using str_replace along with preg_replace

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

问题描述

我有一个逗号分隔的值字符串,这些值来自数据库,实际上是图像路径.像这样:

I have a string of comma separated values that comes from a database, which actually are image paths. Like so:

/images/us/US01021422717777-m.jpg,/images/us/US01021422717780-m.jpg,/images/us/US01021422717782-m.jpg,/images/us/US01021422718486-m.jpg

然后,我像下面那样,在,处将它们拆分,并将它们转换为网页的路径.

I then do like below, to split them at the , and convert them into paths for the web page.

preg_replace('~\s?([^\s,]+)\s?(?:,|$)~','<img class="gallery" src="$1">', $a)

效果很好,但是在页面的另一处,我需要将-m更改为-l(这意味着较大)

Works well, but in one place further in my page, I need to change the -m to -l (which means large)

当我像下面那样(将str_replace放在preg_replace内)时,什么也没发生.我该怎么做?

When I do like below (put a str_replace inside the preg_replace), nothing happens. How can I do something like this?

preg_replace('~\s?([^\s,]+)\s?(?:,|$)~','<img class="gallery" src="$1" data-slide="'.str_replace('-m','-l','$1').'">', $a)

推荐答案

您正在将str_replace()调用放在preg_replace()调用的输出模式中.这意味着preg_replace()会将其视为文字文本.

You're putting the str_replace() call in the output pattern for the preg_replace() call. That means preg_replace() is treating it as literal text.

您想要的是这样的

$imgtag = preg_replace(match, replacement, $a);
$imgtag = str_replace('-m','-l',$imgtag);

但是,我认为,如果您更改替换操作的顺序,调试这些内容会更安全,更轻松,例如:

But, in my opinion it would be safer and easier to debug this stuff if you changed the order of your replacement operations, something like this:

foreach ($path in explode(",", $a)) {
  $path = str_replace('-m','-l',$path);
  $imgtag= sprintf ('<img class="gallery" src="%s">', $path);
  /* do something with the $imgtag */
}

这样一来,您不必吹口哨调制解调器:-)即可对该正则表达式进行编程.

That way you don't have to whistle into your modem :-) to program that regexp.

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

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