I can see two ways to do that, but in the end it's all pretty similar:
replacing the part
As you use str_replace
in your question and you put a NUL byte in there to end a string (like perhaps in C), what you're probably looking for is substr_replace
:
$string = "Hello World; lorem ipsum dolor";
$pos = strpos($string, ";");
if ($pos !== FALSE) {
$string = substr_replace($string, "", $pos);
}
var_dump($string); // string(11) "Hello World"
extracting the part
This is was most of the other answers suggest. Here is even another alternative function for that, you're perhaps looking for the strstr()
function:
$result = strstr($string, ";", true);
This function call with the third parameter set to true returns all of $string
until the needle (second parameter) ";
" is found (excluding it).
Full example:
$string = "Hello World; lorem ipsum dolor";
$result = strstr($string, ";", true);
var_dump($result); // string(11) "Hello World"
Depending on how it should work when ";
" is part or not part of the string, you need to add the needed once if you want to return the full string:
$result = strstr("$string;", ";", true);
This is similar if you operate with strpos()
, you have to deal with FALSE
case as well.