PHP string Replace the end of the string

I need to replace some string to the end of the string or cut the string when it received ";" sign?

Im trying, but it does not work:

$string = "Hello World; lorem ipsum dolor";
$string = str_replace(";","\0",$string);
echo $string; //I want the result is "Hello World"
+4
source share
4 answers

I see two ways to do this, but in the end it all looks pretty similar:

replacing part

As you use str_replacein your question, and you put a zero byte in there to put an end to the line (for example, perhaps in C), what you are probably looking for 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"

part extraction

That was most of the other answers. Here is another alternative function to do this: you are probably looking for a strstr()function : $ result = strstr ($ string, ";", true);

, true, $string, ( ) ";".

:

$string = "Hello World; lorem ipsum dolor";
$result = strstr($string, ";", true);
var_dump($result); // string(11) "Hello World"

, , ";" , , :

$result = strstr("$string;", ";", true);

, strpos(), FALSE.

+2

:

<?php

    $string = "Hello World; lorem ipsum dolor";
    echo $string = substr($string, 0, strpos($string, ";"));

?>

:

Hello World
+4

; ( ).

echo explode(';', $string, 2)[0];

explode()

+3

";" on strpos http://php.net/manual/de/function.strpos.php

echo substr($string, 0, strpos($string, ";"));
+2

Source: https://habr.com/ru/post/1568746/


All Articles