I have a small problem. I am tryng to convert a string like "1 234" to a number:1234
I cant't get there. The string is scraped fro a website. It is possible not to be a space there? Because I've tried methods like str_replace and preg_split for space and nothing. Also (int)$abc takes only the first digit(1).
If anyone has an ideea, I'd be greatefull! Thank you!
This is how I would handle it...
<?php
$string = "Here! is some text, and numbers 12 345, and symbols !£$%^&";
$new_string = preg_replace("/[^0-9]/", "", $string);
echo $new_string // Returns 12345
?>
intval(preg_replace('/[^0-9]/', '', $input))
Scraping websites always requires specific code, you know how you receive the input - and you write code that is required to make it usable.
That is why first answer is still str_replace.
$iInt = (int)str_replace(array(" ", ".", ","), "", $iInt);
$str = "1 234";
$int = intval(str_replace(' ', '', $str)); //1234
I've just came into the same issue, however the answer that was provided wasn't covering all the different cases I had...
So I made this function (the idea popped in my mind thanks to Dan) :
function customCastStringToNumber($stringContainingNumbers, $decimalSeparator = ".", $thousandsSeparator = " "){
$numericValues = $matches = $result = array();
$regExp = null;
$decimalSeparator = preg_quote($decimalSeparator);
$regExp = "/[^0-9$decimalSeparator]/";
preg_match_all("/[0-9]([0-9$thousandsSeparator]*)[0-9]($decimalSeparator)?([0-9]*)/", $stringContainingNumbers, $matches);
if(!empty($matches))
$matches = $matches[0];
foreach($matches as $match):
$numericValues[] = (float)str_replace(",", ".", preg_replace($regExp, "", $match));
endforeach;
$result = $numericValues;
if(count($numericValues) === 1)
$result = $numericValues[0];
return $result;
}
So, basically, this function extracts all the numbers contained inside of a string, no matter how many text there is, identifies the decimal separator and returns every extracted number as a float.
One can specify what decimal separator is used in one's country with the $decimalSeparator parameter.
Use this code for removing any other characters like .,:"'\/, !##$%^&*(), a-z, A-Z :
$string = "This string involves numbers like 12 3435 and 12.356 and other symbols like !## then the output will be just an integer number!";
$output = intval(preg_replace('/[^0-9]/', '', $string));
var_dump($output);
Related
I want to find a number in a string, add one to it, and replace it. These don't work:
$new_version =
preg_replace("/str\/(\d+)str/", "str/".("$1"+1)."str", $original);
$new_version =
preg_replace("/str\/(\d+)str/", "str/".(intval("$1")+1)."str", $original);
Where 'str' is a very identifiable string, each side of the number (and does not contain numbers).
I realise I can do this in more than one line of code quite easily but it seems like this should be possible.
Using a callback function allows you to cast a match to number and increment, e.g.:
preg_replace_callback(
"/str\/(\d+)str/",
function($matches) { return "str/" . ((int)$matches[1] + 1) . "str"; },
$original
);
Solely using str_replace you can get the number from the string, add one to it, and the replace the old number with the new one :
$str = 'In My Cart : 11 items';
$nb = preg_replace('/\D/', '', $str);
$nb += 1;
$str = str_replace($nb-1, $nb, $str);
echo $str;
I'm trying to get all numeric before space/alpha in PHP string.
Example:
<?php
//string
$firstStr = '12 Car';
$secondStr = '412 8all';
$thirdStr = '100Pen';
//result I need
firstStr = 12
SecondStr = 412
thirdStr = 100
How do I can get all the number of a string just like example above?
I've an idea to get the position of first Alpha, then get all numeric before that position.
I've successfully get the position using
preg_match('~[a-z]~i', $value, $match, PREG_OFFSET_CAPTURE);
But I'm not done yet to get the numeric before the posisition.
How do I can do that, or anybody know how to fix my idea?
Anyhelp will be appreciated.
You don't need to use regex for strings like the examples you've shown, or any functions at all for that matter. You can just cast them to ints.
$number = (int) $firstStr; // etc.
The PHP rules for string conversion to number will handle it for you.
However, because of those rules, there are some other types of strings that this won't work for. For example, '-12 Car' or '412e2 8all'.
If you do use a regex, be sure to anchor it to the beginning of the string with ^ or it will match digits anywhere in the string as the other regex answers here do.
preg_match('/^\d+/', $string, $match);
$number = $match[0] ?? '';
Here's an extremely hackish approach that will work in most situations:
$s = "1001BigHairyCamels";
$n = intval($s);
$my_number = str_replace($n, '', $s);
$input = '100Pen';
if (preg_match('~(\d+)[ a-zA-Z]~', $input, $m)) {
echo $m[1];
}
This function will do the job!
<?php
function getInt($str){
preg_match_all('!\d+!', $str, $matches);
return $matches[0][0];
}
$firstStr = '12 Car';
$secondStr = '412 8all';
$thirdStr = '100Pen';
echo 'firstStr = '.getInt($firstStr).'<br>';
echo 'secondStr = '.getInt($secondStr).'<br>';
echo 'thirdStr = '.getInt($thirdStr);
?>
I have a string with a large list with items named as follows:
str = "f05cmdi-test1-name1
f06dmdi-test2-name2";
So the first 4 characters are random characters. And I would like to have an output like this:
'mdi-test1-name1',
'mdi-test2-name2',
As you can see the first characters from the string needs to be replaced with a ' and every line needs to end with ',
How can I change the above string into the string below? I've tried for ours with 'strstr' and 'str_replace' but I can't get it working. It would save me a lot of time if I got it work.
Thanks for your help guys!
Here is a way to do the job:
$input = "f05cmdi-test1-name1
f05cmdi-test2-name2";
$result = preg_replace("/.{4}(\S+)/", "'$1',", $input);
echo $result;
Where \S stands for a NON space character.
EDIT : I deleted the above since the following method is better and more reliable and can be used for any possible combination of four characters.
So what do I do if there are a million different possibillites as starting characters ?
In your specific example I see that the only space is in between the full strings (full string = "f05cmdi-test1-name1" )
So:
str = "f05cmdi-test1-name1 f06dmdi-test2-name2";
$result_array = [];
// Split at the spaces
$result = explode(" ", $str);
foreach($result as $item) {
// If four random chars take string after the first four random chars
$item = substr($item, 5);
$result_array = array_push($result_arrray, $item);
}
Resulting in:
$result_array = [
"mdi-test1-name1",
"mdi-test2-name2",
"....."
];
IF you would like a single string in the style of :
"'mdi-test1-name1','mdi-test2-name2','...'"
Then you can simply do the following:
$result_final = "'" . implode("','" , $result_array) . "'";
This is doable in a rather simple regex pattern
<?php
$str = "f05cmdi-test1-name1
f05cmdi-test2-name2";
$str = preg_replace("~[a-z0-9]{1,4}mdi-test([0-9]+-[a-z0-9]+)~", "'mdi-test\\1',", $str);
echo $str;
Alter to your more specific needs
I have few strings where i need to extract only the prices in php (which will obviously be numerals).
The use cases are follows:
1) Rs. 23,459.45 desired output = 23459.45
2)Our best price 23,459.45 desired output = 23459.45
etc.
I gave the above use cases to give an idea that the preceding characters could be anything.
Please help!
How about:
$arr = array(
'Rs. 23,459.45 ',
'Our best price 23,459.45 ',
);
foreach($arr as $string) {
$string = preg_replace('/^.*?(\d+),?(\d{3})(\.\d{2})?.*$/', "$1$2$3", $string);
echo $string,"\n";
}
output:
23459.45
23459.45
It's:
$result = preg_replace('/[^0-9.]/', '', $string);
-but note, this will not validate numbers or provide valid result in common case since string could contain something like 'foo . bar,baz . price 20.5 with .6 discount' - end result will be not a valid number. So code above answers the question about "how to replace", but does not fit validating a number (and you've not mentioned if that is your goal).
About validating a number - such question will be ambiguous because it's not obvious how to convert ..20.5.6 (which will be result for string above). But if you need only to check that, use is_numeric() on $result, like this:
$string = 'foo . bar,baz . price 20.5 with .6 discount';
$result = preg_replace('/[^0-9.]/', '', $string);
$result = is_numeric($result)?(float)$result:null;
You can use this to validate the above strings. When this function valiadates Rs. , it will return two dots, so I used ltrim to remove the first dot.
<?php
//$s = "Rs. 23,459.45";
$s= "Our best price 23,459.45";
echo $result = ltrim(preg_replace("/[^0-9.]+/", "", $s),'.');
?>
http://codepad.org/cyH5OWyE
I am making application where I receive a string from user. The string is concatenated with - character between them. First part of string contains alphabetic data whereas later part contains integers or floating point numbers. For example: A string might be 3 Cups Tea-5.99.I want to get the later part of string 5.99 separated by - character. How to do that? I know about PHP substr() function but that takes fixed characters to retrieve substring from. But in this case the later part will not be fixed. For example: 2 Jeans-65.99. In this case I would need last 4 characters meaning that I can't use substr() function.
Anybody with solution?
I know I would need to apply regex but I am completely novice in Regex.
Waiting for your help.
Thanks!
Simply
$result = explode('-', $string)[1];
For PHP<5.4 you'll have to use temporary variable:
$data = explode('-', $string);
$result = $data[1];
Edit
As mentioned in comments, if there is more than 1 part, that will be:
$result = array_pop(explode('-', $string));
$bits = explode('-', $inputstring);
echo $bits[1];
You can use substr() with strpos():
$str = '3 Cups Tea-5.99';
echo substr($str, strpos($str, "-") + 1);
Output:
5.99
Demo!
If data will be like this: "1-Cup tea-2.99", then
$data = "1-Cup tea-2.99";
$data = explode('-', $string);
$result = $data[count($data)-1];