1
I have the following code:
$numeros = "142-22";
I just need "142" and I want to ignore the rest of "-22". How do I do it?
Expected exit:
$numeros = "142-22";
$num = "142";
Is there a function I can use?
1
I have the following code:
$numeros = "142-22";
I just need "142" and I want to ignore the rest of "-22". How do I do it?
Expected exit:
$numeros = "142-22";
$num = "142";
Is there a function I can use?
4
PHP already has its own function for this:
$final = strstr($numeros,'-',true);
See working on IDEONE.
Handbook: https://secure.php.net/manual/en/function.stristr.php
There are other ways:
$final = explode('-',$numeros)[0];
See working on IDEONE.
Handbook: https://secure.php.net/manual/en/function.explode.php
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];
0
You can use replace()
(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
0
$numeros = "142-22";
$num = substr($numeros,0,strpos($numeros,"-"));
echo $num;
I used the substr()
to bring the characters from the first to the position that the found the "-", the good thing is that no matter how many characters have before the "-" it will always bring everything.
Hug I hope I helped.
Browser other questions tagged php string
You are not signed in. Login or sign up in order to post.
I did not understand the negative in his, however I had already given +1 (we practically posted together, and it is the same solution of my 2nd alternative - technically you even posted before my Edit, if it is "time")
– Bacco
I don’t understand either... it’s life!
– caiocafardo