Papa De Beau Papa De Beau - 4 months ago 36
PHP Question

PHP remove entire word from string if contains

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?"

Answer

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;
Comments