Php 如果找到特定字符串,如何更改href值

Php 如果找到特定字符串,如何更改href值,php,Php,如果找到某个字符串,如何更改href值 $string ='<a href="http://facebook.com/feelingblue">Facebook</a>' $string='' 如果在href上找到facebook,请替换为仅facebook.com使用此代码 $string ='<a href="http://facebook.com/feelingblue">Facebook</a>'; echo preg_replace(

如果找到某个字符串,如何更改href值

$string ='<a href="http://facebook.com/feelingblue">Facebook</a>'
$string=''
如果在href上找到facebook,请替换为仅facebook.com使用此代码

$string ='<a href="http://facebook.com/feelingblue">Facebook</a>';
echo preg_replace('#http://facebook.com/([^"]+)#is', 'http://www.facebook.com', $string );
$string='';
echo preg_更换('#http://facebook.com/([^“]+)#是','http://www.facebook.com“,$string);
谢谢
Amit

如果要从整个文档中搜索,请使用RegExp

preg_replace_callback('(<a href=")([^"]+)(">([^<]+)</a>)', function($match){
    return $match[1] . "//example.com" . $match[3];
}, $html);

preg\u replace\u回调(”(我假设您从
DB

$url = 'http://facebook.com/feelingblue'; // this is the url you are getting

if (strpos($url , 'facebook') !== false) {
    $url = "https://facebook.com";
}

$string ='<a href="'.$url.'">Facebook</a>'
$url='1!'http://facebook.com/feelingblue“;//这是您正在获取的url
if(strpos($url,'facebook')!==false){
$url=”https://facebook.com";
}
$string=''
要了解更多信息,请尝试以下内容

$string ='<a href="http://facebook.com/feelingblue">Facebook</a>';
if (strpos($string, 'facebook') !== false) {
    $facebookUrl = "http://www.facebook.com";
    $regEx = "/(?<=href=(\"|'))[^\"']+(?=(\"|'))/";
    $newUrl = preg_replace($regEx,$facebookUrl,$string);
}
echo $newUrl;
$string='';
if(strpos($string,'facebook')!==false){
$facebookUrl=”http://www.facebook.com";
$regEx=“/(?您的字符串是:-

$str ='<a href="http://facebook.com/feelingblue">Facebook</a>';
删除.com之后的其他内容

$url = preg_replace ('/(\.com).*/','$1',$url);
期望的产出将是

facebook.com


http://facebook.com/feelingblue
手动放置或您正在通过
DB
获取。您是否询问如何将
$string=''
更改为
$string=''
?facebook.com/*之后的任何内容都将被替换。这就像一个符咒。不过,接下来可能是http://或www或https://或通配符?所以我不必指定#^“]+)#也只有a href,可能还有其他string实例我知道这不是一个好的修复方法,但我现在这样做了echo preg_replace('#href=“^”]+)#is',''$string);因为还有其他字符串包含facebook.com或其他related@user3240742要替换facebook字符串之前或之后的任何内容,这应该有效。$string='',$string);这是一个问题,如果我有,它将替换

中的文本。我需要它只是href
$url = str_replace ('http://', '', $matches[2]);
$url = preg_replace ('/(\.com).*/','$1',$url);