How do I remove characters from a string up to a point? in PHP [duplicate]

1

I have the following code:

$numeros = "142-22";

I just need "142" and I want to ignore the rest "-22". How do I do this?

Expected output:

$numeros = "142-22";
$num = "142";

Is there a function that I can use?

    
asked by anonymous 15.08.2018 / 18:17

4 answers

4

PHP already has its own function for this:

$final = strstr($numeros,'-',true);

See working at IDEONE .

  

Manual: link


There are other ways:

$final = explode('-',$numeros)[0];

See working at IDEONE .

  

Manual: link

    
15.08.2018 / 18:43
1

Using the explode:

$string = "142-22";
// da um explode usando o - como separador
$stringSeparada = explode("-", $string);
// a $stringSeparada vira uma array, e i primeiro elemento dessa array é a parte inicial antes do caractere -
echo $stringSeparada[0]; 
    
15.08.2018 / 18:43
0
$numeros = "142-22";
$num = substr($numeros,0,strpos($numeros,"-"));
echo $num;

I've used substr() to bring the characters from the first to the position where the "-" is found, the good this way is that no matter how many characters you have before the "-" it will always bring everything. / p>

I hope to have helped.

    
15.08.2018 / 18:26
0

You can use substr ()

  

(PHP 4, PHP 5, PHP 7)

     

substr - Returns a part of a string

     

Source: here

$string = "142-22";

echo substr($string, 0, 3);

See an example working on PHP Sandbox

    
15.08.2018 / 18:24