4

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

Im trying but it doesnt work :

$string = "Hello World; lorem ipsum dolor";
$string = str_replace(";","\0",$string);
echo $string; //I want the result is "Hello World"
hakre
  • 193,403
  • 52
  • 435
  • 836
GandhyOnly
  • 325
  • 2
  • 5
  • 18

4 Answers4

4

This should work for you:

<?php

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

?>

Output:

Hello World
Rizier123
  • 58,877
  • 16
  • 101
  • 156
3

You need to split the string with ; and get first element from the returned array (it will always have at least one entry).

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

explode()

hakre
  • 193,403
  • 52
  • 435
  • 836
Pupil
  • 23,834
  • 6
  • 44
  • 66
2

cut the rest from ";" on with strpos from http://php.net/manual/de/function.strpos.php

echo substr($string, 0, strpos($string, ";"));
Max
  • 336
  • 1
  • 12
2

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.

hakre
  • 193,403
  • 52
  • 435
  • 836