はちょうどあなたの問題への完璧なソリューションを書かれている:あなたはあなたのを持ちたい方法に応じて
string(302) "After the latest show, we went to <a href="http://www.example.com">www.example.com</a> and made some trouble online. <a href="https://www.letsfail.net/?a=b">www.letsfail.net/?a=b</a> gave us their support and also <a href="http://netjunkies.sample">netjunkies.sample</a> is involved. Finally we are in!"
:
$demo = "After the latest show, we went to www.example.com and made some trouble online. https://www.letsfail.net/?a=b gave us their support and also netjunkies.sample is involved. Finally we are in!";
var_dump(webAddressesToHTML($demo));
出力:
function webAddressesToHTML($text,$label_strip_params=false,$label_strip_protocol=true) {
$webAddressToHTML = function ($url) use ($label_strip_params,$label_strip_protocol) {
$label = $url;
if($label_strip_params) {
$label = rtrim(preg_replace('/\?.*/', '',$label),"/");
}
if($label_strip_protocol) {
$label = preg_replace('#^https?://#', '', $label);
}
return '<a href="'.((!preg_match("~^(?:f|ht)tps?://~i", $url)) ? "http://".$url : $url).'">'.$label.'</a>';
};
preg_match_all('@(http(s)?://)?(([a-zA-Z])([-\w]+\.)+([^\s\.]+[^\s]*)+[^,.\s])@',$text,$matched_urls);
return str_replace($matched_urls[0],array_map($webAddressToHTML,$matched_urls[0]),$text);
}
は、例を参照してください。ウェブアドレスラベルは、オプションのパラメータをtrue
に設定するだけですr false
。実際にパラメータを取り除きたい場合は、ユースケースによって異なります。
http://www.websitename.com?title=oy96をhttp://www.websitename.comに変換することを意味しますか? –
おそらくhttps://regex101.com/r/1LgEps/2/またはプロトコルも削除する必要がある場合は、それを独自のキャプチャグループに移動してください。 – chris85
あなたの理由があるかもしれませんが、それはユーザーインターフェイスのために悪いかもしれません。同じドメインが異なる記事で何度か言及されるとどうなるでしょうか? – Martijn