str_replace()无法按预期工作

时间:2015-05-15 06:59:19

标签: php regex str-replace

我正在尝试使用$content替换字符串str_replace中图片的src属性。

这些图片的../img/article/foo.jpg通常会链接到img/article/foo.jpg,但我希望每次迭代都设置为$content = str_replace('../img/article', 'img/article', $content);

我的代码是这样的:

$content

这不会对function remove_styles($text) { $content = trim($content); $content = preg_replace('#(<[a-z ]*)(style=("|\')(.*?)("|\'))([a-z ]*>)#', '\\1\\6', $text); $content = preg_replace('/(<[^>]+) style=".*?"/i', '$1', $content); $content = strip_tags($content,'<h2><h3><p><strong><a><ul><li><img>'); $content = str_replace('../img/article','img/article',$content); return $content; } 返回任何更改。

我做错了什么?

修改

以下是清理用户输入的完整功能:

<p data-wr_replaced="true">Your job search has gone well. You've aced the interviews, you've worked through the technical tests, you've wowed the partners and you've finally got the offer you were looking for at the firm you've always wanted to work at.</p>
<p data-wr_replaced="true">But when you want to resign, your current workplace offers you more. More money, more holiday, more opportunity.</p>
<p data-wr_replaced="true">Now I'm not going to say what you should or shouldn't do - there are plenty of other guides giving you very clear advice out there:</p>
<p> <img src="../img/article/6a3184a558a98656e900f4aa106c387c.png" alt="" width="479" height="662" /></p>

这会删除样式,修剪空格,剥离标记并更正相对路径。

内容来自TinyMCE编辑器,示例如下:

if __name__ == '__main__':

图像通过WYSIWYG编辑器上传并保存相对路径,该路径在文章最终显示的页面上不正确。

3 个答案:

答案 0 :(得分:0)

虽然您的代码看起来很好。如果仍然无法使其正常工作,请尝试使用preg_replace。

这将匹配任何链接,即“../”并将其删除。如果你只想做img / etc,那么用括号更改部分。

$content = '../img/article/ttt.jpg';
$content = preg_replace('/\.\.\/(.+)/', '$1', $content);
echo $content;

如果你想摆脱'../'的多个级别,那么:

$content = '../../img/article/ttt.jpg';
$content = preg_replace('/(\.\.\/)+(.+)/', '$2', $content);
echo $content;

Demo of the above code here.

答案 1 :(得分:0)

您可以将捕获分组与preg_replace功能一起使用:

$content = preg_replace('/[\w/]+/(\w+/\w+)/i', '$1', $content);

Demo

答案 2 :(得分:0)

我认为这是你想要做的? 找到$ content中的链接(由用户发布)并将图像中的网址从“../”替换为“/”

$content = "<h1>This is the article header</h1> <p>This is a paragraph</p> <img src='..img/article/foo.jpg' alt='this is a image which src i want to replace'/>";

$find = "..img/article";
$replace = "img/article";
$content = str_replace($find,$replace,$content);

echo $content;

http://www.tehplayground.com/#ujK2N2ldQ