jeffimperial
jeffimperial

Reputation: 73

php preg_replace all characters after whitespace in each line

I have a script that outputs an array that, when each item in the array is printed out, gives me

https://media.com/2db93b9.jpg Ann
https://media.com/3198676.jpg Lin
https://media.com/ David
https://media.com/0f48c22.jpg Ulrich
https://media.com/135f3b7.jpg David

I am trying to drop the space, and everything else after it with the following preg_replace

foreach($rows as $row) {
    $row = preg_replace("[\\ ].*", "", $row);
    echo $row . '<br />';
}

According to http://regexr.com, that pattern of mine should work. But when I have tried both /[\\ ].*/g and [\\ ].*. Neither works. It says php met an unknown modifier. Obviously, I'm no regular expressions expert, and I would love any kind of help.

Upvotes: 1

Views: 1057

Answers (1)

anubhava
anubhava

Reputation: 786291

You need to use:

$row = preg_replace('/ .*$/', "", $row);

Or:

$row = preg_replace('/\s.*$/', "", $row);
  • Regex needs a delimiter in PHP
  • Correct regex should a space and everything thereafter using .*$
  • \s matches space OR tab or newline

Upvotes: 3

Related Questions