【问题标题】:Removing url / domain from string with parentheses从带括号的字符串中删除 url / domain
【发布时间】:2018-03-29 22:29:19
【问题描述】:

有没有办法从给定的带括号的字符串中查找和删除 url 或域?

示例:(like someurl.com) 应该是 (like) 并且 [like someurl.com] 变成 [like] ... 还有 [like someurl.com/path/something.html] 应该是 [like]

也许有人可以帮助我编写代码来执行此操作。

【问题讨论】:

  • 正则表达式是你要找的
  • 尝试使用preg_replace()。我看到了你的标签,但你有什么尝试?
  • 我设法从字符串中替换了 url/domain,但我不能在括号中这样做...
  • 你可能想看看这个this answer
  • 我将此代码用于字符串替换 stackoverflow.com/questions/1113840/php-remove-url-from-string 但它只替换 ( ) 和 [ ] 之外的内容。

标签: php regex string replace preg-replace


【解决方案1】:
$str = "(like someurl.com)";
$index_dot =  $index_space_before_dot = $index_after_dot = -1;
for($i=0; $i<strlen($str); $i++){
    if($str[$i] == '.'){
        $index_dot = $i;
    }

    if($str[$i] == ' '  && $index_dot == -1 && $index_space_before_dot == -1){
        $index_space_before_dot = $i;
    }elseif ($str[$i] == ' '  && $index_dot > -1){
        $index_space_before_dot = $i;
    }
}

$str = substr($str, 0, $index_space_before_dot);
echo $str . ')'; 

【讨论】:

    【解决方案2】:

    你需要一个Regular Expression (regx) 这里

    $string_with_url = 'lorem (like GOoogle.COM someurl.com/path/something.html ) lipsum';
    
    $string_without_url = preg_replace("/(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)?[a-zA-Z0-9]+([\-\.]{1}[a-zA-Z0-9]+)*\.[a-zA-Z]{2,5}(:[0-9]{1,5})?(\/.+[a-zA-Z\/]\s)?/", "", $string_with_url);
    
    echo $string_without_url; // lorem (like ) lipsum
    

    【讨论】:

    • 这适用于小写域名,大写域名不会被替换,或者如果域名是:someDomain.com 仅替换 omain.com,它将编码为 someD
    猜你喜欢
    • 2012-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多