[英]php regular expression preg_replace
我有以下代碼(php),它將匹配img-src並替換為新的網址
$rep = array('/', '+', '(', ')');
$with = array('\/', '\+', '\(', '\)');
$match_pattern = '/<img[^<]*src\s*=\s*\"'.str_replace($rep, $with, $source_url).'\"[^>]*>/iUu';
$img_replace_str = '<img src="'.$new_url.'" />';
$post_content = preg_replace($match_pattern, $img_replace_str, $post_content);
對於src為“http://www.example.com/a.jpg”的圖像,沒有問題,但對於src包含查詢字符串的圖像,如“http://www.example.com/b” .jpg?height = 900“,不匹配
我希望匹配帶有和不帶查詢字符串的圖像。
您可以使用PHP的preg_quote()
函數而不是str_replace()
。 它會自動轉義所有正則表達式特殊字符(請參閱文檔)。 這應該可以解決問題,因為你的str_replace()
solution沒有逃脫?
,這是正則表達式中的特殊字符:
$match_pattern = '/<img[^<]*src\s*=\s*\"'.preg_quote($source_url, '/').'\"[^>]*>/iUu';
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.