Reputation: 544
I have a string like "Car version XXXX".
I want to remove all after "version" but keep this first part. The final should be "Car version"
Currently, I managed to do this:
$version = "Car version 15282";
$version = substr($version, 0, strpos($version, "version"));
echo $version;
But it removes the string "version" also and I need to keep it. In the web I only see example to remove after the character including this last.
How to achieve this in PHP ?
Upvotes: 0
Views: 57
Reputation: 78994
Since you know what you're looking for you just need one function:
$version = "Car version 15282";
$find = "version";
$version = strstr($version, $find, true) . $find;
If it could get more complex, match and capture ()
everything up to and including what you want to find .*
and $find
and replace that and everything after .*
with what you captured $1
:
$version = preg_replace("/(.*$find).*/", "$1", $version);
Upvotes: 2
Reputation: 94672
You need to add on the length of the string you are searching for because strlen()
gives you the index of where the string version
starts.
$version = "Car version 15282";
$version = substr($version, 0, strpos($version, "version")+strlen("version"));
echo $version;
Gives Result
Car version
Upvotes: 2