Reputation:
I have a string like "1X6TAB". Now I apply some regular expression to this string to remove "TAB" and replacing "X" with "*", so my final string will be "1*6". The expected result is "6", but I get "1*6" as the result.
Code:
Regexonlynumber("1X6TAB");
function Regexonlynumber($number){
$number = preg_replace("/[^0-9.X]/", '', $number);
echo str_replace('X',"*",$number);die;
}
Upvotes: 7
Views: 1424
Reputation: 4557
array_product() Function :- The array_product() function calculates and returns the product of an array.
str_split() Function :- The str_split() function splits a string into an array.
<?php
function Regexonlynumber($number){
$number = preg_replace("/[^0-9,.]/", "", $number);
echo array_product(str_split($number));
}
Regexonlynumber("1X6TAB");
?>
Upvotes: 2
Reputation: 11277
It's better to use eval()
, which will also be able to compute more complex expressions:
Regexonlynumber("3X6-13TAB");
function Regexonlynumber($number){
$number = preg_replace("/[^0-9.X\-\+\/]/", '', $number);
$str = str_replace('X',"*",$number);
eval("\$result = {$str};");
echo $str . " = " . $result . "\n";
}
Upvotes: 2
Reputation: 34914
You are almost there. Just add one step more to explode and multiply, like this:
<?php
function Regexonlynumber($number){
$number = preg_replace("/[^0-9.X]/", '', $number);
$arr = explode("X", $number);
echo $arr[0]*$arr[1];
}
Regexonlynumber("2X6TAB");
?>
Demo.
You can even just do it like:
function Regexonlynumber($number){
$arr = explode("X", $number);
echo $arr[0]*$arr[1];
}
Demo.
Upvotes: 3
Reputation: 1026
Instead of str_replace()
, you can explode()
it by 'X'
delimiter, then use array_product()
.
Regexonlynumber("1X6TAB");
function Regexonlynumber($number){
$number = preg_replace("/[^0-9.X]/", '', $number);
echo array_product(explode('X', $number));
}
Upvotes: 12