簡體   English   中英

php:從字符串中刪除URL

[英]php: Remove URL from string

我有許多字符串(推文推文),當我回應它時,我想從中刪除鏈接。

我無法控制字符串,即使所有鏈接都以http開頭,它們也可以以“/”或“;”結尾。 沒有,被跟蹤或不被空間跟隨。 此外,有時鏈接和它之前的單詞之間沒有空格。

這種字符串的一個例子:

The Third Culture: The Frontline of Global Thinkinghttp://is.gd/qFioda;via @edge

我嘗試使用preg_replace,但無法提出適合所有異常的解決方案:

<?php echo preg_replace("/\http[^)]+\;/","",$feed->itemTitle); ?>

知道我該怎么辦嗎?

編輯:我試過了

<?php echo preg_replace('@(https?://([-\w\.]+[-\w])+(:\d+)?(/([\w/_\.#-]*(\?\S+)?[^\.\s])?)‌​?)@', ' ', $feed->itemTitle); ?>

但仍然沒有成功。

編輯2:我找到了這個:

<?php echo preg_replace('^(ht|f)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-‌​\.\?\,\'\/\\\+&amp;%\$#_]*)?$^',' ', $feed->itemTitle); ?>

它會按預期刪除鏈接,但當鏈接與其前面的單詞之間沒有空格時,它也會刪除整個字符串。

如果你想刪除所有內容,鏈接和鏈接后,例如通過你的例子中的東西,下面可能會幫助你:

$string = "The Third Culture: The Frontline of Global Thinkinghttp://is.gd/qFioda;via @edge";
$regex = "@(https?://([-\w\.]+[-\w])+(:\d+)?(/([\w/_\.#-]*(\?\S+)?[^\.\s])?).*$)@";
echo preg_replace($regex, ' ', $string);

如果你想保留它們:

$string = "The Third Culture: The Frontline of Global Thinkinghttp://is.gd/qFioda;via @edge";
$regex = "@(https?://([-\w\.]+[-\w])+(:\d+)?(/([\w/_\.#-]*(\?\S+)?[^\.\s])?)?)@";
echo preg_replace($regex, ' ', $string);

我會做這樣的事情:

$input = "The Third Culture: The Frontline of Global Thinkinghttp://is.gd/qFioda;via @edge";
$replace = '"(https?://.*)(?=;)"';

$output = preg_replace($replace, '', $input);
print_r($output);

它也適用於多次出現:

$output = preg_replace($replace, '', $input."\n".$input);
print_r($output);

暫無
暫無

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

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