How do I remove characters from a string to a certain extent? in PHP

Asked

Viewed 360 times

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 answers

4

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]; 
  • 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")

  • I don’t understand either... it’s life!

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

You are not signed in. Login or sign up in order to post.