Delete parentheses with php

Asked

Viewed 866 times

1

How do I eliminate parentheses and the trait of this variable in php ?

$var = " ( 1 ) - ( 2 ) ";

Final result:

It would be an array separating the numbers, example:

 x[0]; -> 1
 x[1]; -> 2

I would like to have the parentheses and the trait and saved in arrays only the numbers.

  • In case (1) - (2) is coming as string ?

  • It is stored inside the $var variable and this as a string. $var = "(1) - (2)";

  • How would the end result be? edit your question and ask to understand , how would the answer.

  • i edited the post

1 answer

5

Can use preg_match thus:

<?php

$var = '(1) - (2)';

preg_match('#\((\d+)\) - \((\d+)\)#', $var, $output);

array_shift($output); //Remove o primeiro item, pois não vai usa-lo

print_r($output);

echo 'Primeiro número: ', $output[0], PHP_EOL;
echo 'Segundo número: ', $output[1], PHP_EOL;

Will display this:

Array
(
    [0] => 1
    [1] => 2
)

Primeiro número: 1
Segundo número: 2

So just use it like this:

echo $output[0]; //Pega o primeiro numero
echo $output[1]; //Pega o segundo numero

See the result on ideone

Or you can use preg_match_all to pick up whatever is on the "way":

<?php

$var = '(1) - (2) - (3)';

preg_match_all('#\((\d+)\)#', $var, $output);

$resultado = $output[1];//Pega apenas os números

print_r($resultado);

Will display this:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)

So just use it like this:

echo $resultado[0]; //Pega o primeiro numero
echo $resultado[1]; //Pega o segundo numero
echo $resultado[2]; //Pega o terceiro numero

See the result on ideone

If you still have doubts about how to use arrays, I recommend learning the basics:

And after learning the basics follow the documentation on the functions used:

  • I am asking, because I did this test print_r($output[1]); , This should return me only the value of position 1 of the array, but this returning me all.

  • Returned this: Array ( [0] => 1 [1] => 2 )

  • @abduzeedo edited the answer again and added some links to help :D

  • How cool, in this case this preg_match_all, would serve to take also a word from the front of the number ? example: friend(1) - friend(2). Daria oara to take the word friend and relatives ?

  • @abduzeedo do not need to use preg_match_all for this, just change the Regex between the #...#, do so preg_match('#amigo\((\d+)\) - amigo\((\d+)\)#', $var, $output);... The withpreg_match_all('#\((\d+)\)#', $var, $output);, no need, it recognizes only the numbers.

Browser other questions tagged

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