簡體   English   中英

str_replace() 沒有按預期工作

[英]str_replace() not working as expected

我正在嘗試使用str_replace替換字符串$content中圖像的src屬性。

這些圖像的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;
}

這將刪除樣式、修剪空白、去除標簽並更正相對路徑。

內容來自 TinyMCE 編輯器,示例如下:

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

圖片通過所見即所得編輯器上傳並保存相對路徑,在文章最終顯示的頁面上是不正確的。

雖然你的代碼看起來不錯。 如果您仍然無法使其正常工作,請嘗試 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;

上面代碼的演示在這里。

您可以將捕獲分組與preg_replace函數一起使用:

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

演示

我認為這就是你想要做的? 找到 $content 中的鏈接(由用戶發布)並將圖像中的 url 從“../”替換為“/”

$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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM