doudonglu3764 2016-07-24 17:40
浏览 40
已采纳

如果包含,PHP将从字符串中删除整个单词

I have code that displays my tweets. In the tweet the pictures are showing up as urls as are the links. I would like to remove the entire 'WORD' if it is a pic or a link. PS I found threads on here that are close to what I am looking for but do not produce my desired effect.

If it contains a "http" or a ".pic" I then want to remove the entire 'word'.

Here is my code:

<?php


$wordlist = array('http','pic');
 $replaceWith  = "";

/* Sample data */
$words = 'This tweet has a pic.twitter.com/00GeQ3zLub and a url http://www.mywebsite.com';

foreach ($wordlist as $v)
  $words = clean($v, $words, $replaceWith);

function clean($word, $value, $replaceWith) {
    return preg_replace("/\w*$word\w*/i", "$replaceWith ",trim($value));
}

echo $words;
?>

ACTUAL OUTPUT: This tweet has a .twitter.com/00GeQ3zLub and a url ://www.mywebsite.com

DESIRED RESULT: This tweet has a and a url

UPDATE for clarification:
I want to remove any "string of characters with no spaces" that contain a ".pic" or a "http". I don't know how to explain it with the right terms... but if a .pic.twitter.com/ia8akd is in my tweet I want the whole thing gone. Same with anything that contains a "http". I want the WHOLE 'string' gone. for example my tweet is "This is my website: http://www.MyWebsite.com. Pretty cool?" I would like this to display as "This is my website: Pretty cool?"

  • 写回答

3条回答 默认 最新

  • douyan1321 2016-07-24 17:49
    关注

    The \w does not match a ., nor :. You should match all continuos non-whitespace characters around your words.

    \S*(?:http|pic)\S*
    

    This will remove anything starting with pic though, it is not specific to a URL.

    Regex demo: https://regex101.com/r/qZ8tD3/1

    PHP Demo: https://eval.in/611103

    PHP Usage:

    $wordlist = array('http','pic');
     $replaceWith  = "";
    
    /* Sample data */
    $words = 'This tweet has a pic.twitter.com/00GeQ3zLub and a url http://www.mywebsite.com';
    
    foreach ($wordlist as $v)
      $words = clean($v, $words, $replaceWith);
    
    function clean($word, $value, $replaceWith) {
        return preg_replace("/\S*$word\S*/i", "$replaceWith ",trim($value));
    }
    
    echo $words;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 怎样才能让鼠标沿着线条的中心线轨迹移动
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?