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 GD32 SPI通信时我从机原样返回收到的数据怎么弄?
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?