问题描述
假设我在数据库中有以下文字。
$str = 'Test text http://hello-world.com Test text http://google.com/file.jpg?google=1 Test text https://hell.o.wor.ld/test?qwe=qwe Test text text text http://test.test/test hello all how are you I hope you all are fine ';
现在,我要在utm_source和所有网址的中间添加以下内容。
$utmUrl = "utm_source=source&utm_medium=email&utm_campaign=mycamp";
我已经知道我可以找到所有URL并执行str_replace(),但是我想这样做
preg_replace()
让我知道是否有人知道其他解决方案
这里的问题是某些URL已经存在?在URL中标记,所以我需要使用&来设置URL,而在哪里呢?我需要附加吗?
解决方法
由joy建议的编辑
类似这样的东西。
$re ='/(?:(?:https?|ftp|file):\/\/|www\.|ftp\.)(?:\([-A-Z0-9+&@#\/%=~_|$?!:,.]*\)|[-A-Z0-9+&@#\/%=~_|$?!:,.])*(?:\([-A-Z0-9+&@#\/%=~_|$?!:,.]*\)|[A-Z0-9+&@#\/%=~_|$])/im';
$str = 'Test text http://hello-world.com Test text http://google.com/file.jpg?google=1 Test text https://hell.o.wor.ld/test?qwe=qwe Test text text text http://test.test/test hello all how are you I hope you all are fine ';
$utmUrl = "utm_source=source&utm_medium=email&utm_campaign=mycamp";
preg_match_all($re,$str,$matches,PREG_SET_ORDER,0);
foreach ($matches as $match)
$str = preg_replace('%' . $match[0] . '%',$match[0] . (strpos($match[0],'?') !== false ? '&' : '?') . $utmUrl,$str);
var_dump($str);
$re = '/(?:(?:https?|ftp|file):\/\/|www\.|ftp\.)(?:\([-A-Z0-9+&@#\/%=~_|$?!:,.]*\)|[A-Z0-9+&@#\/%=~_|$])/im';
$str = 'Test text http://hello-world.com Test text http://google.com/file.jpg?google=1 Test text https://hell.o.wor.ld/test?qwe=qwe Test text text text http://test.test/test hello all how are you I hope you all are fine ';
$utmUrl = "utm_source=source&utm_medium=email&utm_campaign=mycamp";
$str = preg_replace_callback($re,function ($match) use ($utmUrl) {
return $match[0] . (strpos($match[0],'?') !== false ? '&' : '?') . $utmUrl . ' ';
},$str);
var_dump($str);
旧答案。
类似这样的东西。
$re = '%(https?://.*)\s%mU';
$str = 'Test text http://hello-world.com Test text http://google.com/file.jpg?google=1 Test text https://hell.o.wor.ld/test?qwe=qwe Test text text text http://test.test/test hello all how are you I hope you all are fine ';
$utmUrl = "utm_source=source&utm_medium=email&utm_campaign=mycamp";
preg_match_all($re,0);
foreach ($matches as $match)
$str = preg_replace('%' . $match[1] . '%',$match[1] . (strpos($match[1],$str);
var_dump($str);
$re = '%(https?://.*)\s%mU';
$str = 'Test text http://hello-world.com Test text http://google.com/file.jpg?google=1 Test text https://hell.o.wor.ld/test?qwe=qwe Test text text text http://test.test/test hello all how are you I hope you all are fine ';
$utmUrl = "utm_source=source&utm_medium=email&utm_campaign=mycamp";
$str = preg_replace_callback($re,function ($match) use ($utmUrl) {
return $match[1] . (strpos($match[1],$str);
var_dump($str);