PHP how to get the second number present in a string - php

I would like to get the second number present in a string.
Maybe you have better ideas than mine.
From this example:
1 PLN = 0.07 Gold
I would like to get only "0.07" from that string.
I obtain it from web scraping so it returns me as a string.
The problem that I have is the following.
The "second number in string" might be with ".", without it, might be composed by only one number ex. "1", or by two "12", might have decimals ex. "1.2", even position may change, because for some currency I will have "1 PLN", "1 USD" for others I will have "1 TW".
So I can't work on position, I can't extract only numbers (I have the "1" at the beginning of the string), I can't extract only INT cause I could have also decimals...
So the only constant of that string - I think (but if you have better ideas pls suggest me) - is that I need the second number I find in the string.
How could I get it?
Sorry If I wasn't enough clear.

Try this:
<?php
$string = '1 PLN = 0.07 Gold';
$pattern = '/\d+\.\d+/';
$matches = array();
$r = preg_match($pattern, $string, $matches);
var_dump($matches); //$matches is array with results
Output:
array(1) {
[0]=>
string(4) "0.07"
}

If its always in this format 1 PLN = 0.07 Gold You can just
$array = explode(" ", $string) with a Space and then get the required number with
$number = $array[3]
Try it out, let me know if it works

You can use a simple regex patter to isolate all numbers, including decimals if any after the equals sign.
The below works if the string will have the same structure, meaning an = a space and then the number that you are after.
= - matches the equals sign
\s - matches the space character immediately after
(\d*\.?\d*) - matches any number of digits followed by an optional period . and then any number of digits
$str = '1 PLN = 0.07 Gold';
preg_match('#=\s(\d*\.?\d*)#',$str,$matches);
print $matches[1];
Will output
0.07
This works regardless of what you have before the = sign.

Related

How to split data from a single word string in PHP?

I need to split data from a single word string like below,
$string = "RC9999999999A202";
//Need to split as follows:
$code = "RC"; //This value must be of 2 alphabetic characters
$phone = "9999999999"; //This value must be of 10 digits
$amount = "202"; //This value can be of any length (numeric only)
I tried nothing because I don't have any idea regarding this since I'm a newbie.
Please help!
Please do not leave negative rating, instead try to help me.
If your string will always be like you described 2 chars then 10 digits followed by any number of chars then you can get what you want simply using substr like so :
$string = "RC9999999999A202";
echo $code = substr($string, 0, 2); // get first 2 chars
echo $phone = substr($string, 2, 10); // get 10 chars starting from 3d char
echo $amount = substr($string, 12); // get whatever chars left
Note: this method does not validate any data, it just extract what you have in your string based on what you described in the question.
This will match according to your specifications and populate the variables code, phone and amount.
$string = "RC9999999999A202";
Preg_match("/([A-Z]{2})(\d{10})A(\d+)/", $string, $match);
List($string, $code, $phone, $amount) = $match;
https://3v4l.org/QXVRA
This pattern assumes the "A" is always an "A".
You didn't mention it at all in the question so I assume it's always an "A".
You can use this regex for preg_match:
$str = 'RC9999999999A202';
if (preg_match('/([A-Z]{2})(\d{10})\D*(\d*)/', $str, $m)) {
unset($m[0]); // delete full match from array
print_r($m);
}
Output:
Array
(
[1] => RC
[2] => 9999999999
[3] => 202
)
RegEx Demo

Return xx characters before a certain string

So I have this string:
Best location using 168 cars + cleaning
The '168' is the part i'd like to extract from this string.
I have approximately 80 occurences of this string, all alternating from 'xx' cars to 'xxx' cars (so, 2 or 3 numbers). However, in each string, 'cars' comes after the number i'd like to return.
What would be the best way using PHP to achieve this?
The best way is to do a simple preg_match on the text.
See the tutorial: http://php.net/manual/en/function.preg-match.php
<?php
$string = 'Best location using 168 cars + cleaning';
$pattern = '/(\d{2,3}+) cars/';
preg_match($pattern, $string, $match);
echo $match[1];
This regex returns all the numbers with length of 2 to 3 before the word cars.
you can change the length as you want and \d means all the numbers.
Easiest way is probably via preg_match(). Look for a space, one or more digits, a space, then the word cars. Use parens to capture the digits. That gives you pattern like this:
' (\d+) cars'
Then just pass that to preg_match() with a third argument to capture the parenthesized substring:
if (preg_match('/ (\d+) cars/', $str, $match)) {
echo "your num is: " . $match[1] . "\n";
}
Note this will also capture 1 cars and 1234 cars. If that's a problem, and you want to ensure that you only get the values with two or three digits, you can tweak the pattern to explicitly require that:
' (\d{2,3}) cars'
I would explode the string on a space and then loop through the array looking for the string "cars" and then get the key value for this. From here you know that the number will be before the "cars" occurrence so minus 1 from this key value and look in the array.
$original_string = "Best location using 168 cars + cleaning";
$string = explode(" ", $original_string);
foreach ($string as $key => $part) {
if($part == "cars") {
$number = $string[$key-1];
}
}
Explanation:
$original_string is whatever your whole string where the number is unknown.
$string is an array of the $original_string, each word will be in it's own part of the array
we loop through this array looking for the string "cars" and also get its key value.
If we find it successfully we then go to the key value minus one to find the number. We do this because we know the number appears before the "cars" string.

Wrap all cents values in a string with superscript

I have a string that could be something like "$2.99" or could be "$1.99 - $20.99" with multiple prices in the string.
I would like to wrap the cents in a superscript tag.
So far I have been trying:
$price = [could be "$x.xx" or could be "$x.xx - $xx.xx"];
$pattern = '/(\$[\d,]+\.)(\d+)([\s\-]*\$[\d,]*\.*)(\d*)(.*)$/';
$formattedPrice = preg_replace($pattern, '$1<sup>$2</sup>$3<sup>$4</sup>$5', $price);
But that only matches "$x.xx - $xx.xx" not just "$x.xx"
Is there a good way to just find all instances of a period and wrap the next two characters?
Thanks.
Try this:
$pattern = '/\.([\d]{2})/';
This pattern will match any two digits that are directly following a period.
preg_replace($pattern, '.<sup>$1</sup>', '$2.99');
preg_replace($pattern, '.<sup>$1</sup>', '$1.99 - $20.00');
Output:
string(16) "$2.<sup>99</sup>"
string(36) "$1.<sup>99</sup> - $20.<sup>00</sup>"
If you wanted to guard against not selecting any random two digits following a period but specifically in a dollar amount, you can add to it to ensure you're correctly targetting the right substrings with this pattern:
$pattern = '/\$\d\.([\d]{2})/';
if you want to wrap the cents then you could use:
(\$\d+\.)(\d+)
Working demo

PHP find double digit number before a given word

I need to find either a double or single-digit number that appears before a given word that is buried in a long string. For example find the number of children when given as follows:
Derive 12 from:
blah blah..................12 children............blah blah
or 6 from:
blah blah......6 children.............blah blah
The following code works for single digit but only returns 2 for the double digit
<?php
$body = ("..blah..blah...6 children....");
$children_single = explode ("children", $body);
$num_children = preg_replace("/[^0-9]/","", substr($children_single[0],-2));
echo $num_children;
?>
How do I adjust this to give both a single or double digit result?
Your current condition is failing because of the space. When you explode the string 12 children, the first part, $children_single[0], will contain the string 12 (note the space). So, when you use substr() on that string, the space will be included and will only capture 2 (with the space).
To avoid that, you can start substr() count from the beginning, by using the second parameter, like so:
$num_children = preg_replace("/[^0-9]/","", substr($children_single[0], 0, 2));
Demo!
UPDATE:
As per your comment, the above version won't work if the word children occurs in a long string. In that case, you can use a negative start, as follows:
$num_children = preg_replace("/[^0-9]/","", substr($children_single[0], -3, -1));
Demo!

Regular expression matching in php

I have this regexp:
/(.*)(([0-9]([^a-zA-Z])*){7,}[0-9])(.*)/.
Given the following values
0654535263
065453-.-5263
065asd4535263
Expected Results
06****
06****
06****
Actual Results
0654535263
06****
065asd4535263
It does not match the last row because of the letters (I want to match from 0-3 letters) and it matches only last occurence (in the second row in example, it skips first row).
First of all thank u all oyur answers are very helpfull and i owe u a bih time. I cant create array of numbers and mask them like that because i can have string like this:
I am John, I live bla bla my phone is: 0, 6, 5, 4, 5, 3, 5, 2, 6 - 3 -- 065asd4535263.
To simplify i want to hide entered mobile number.
I had two problems:
change regxp mentioned above, to hide digits separated by no more than 3 chars.
preg_replace was replacing only one occurence.
At the end i just need regexp to replace any array of digits, at least 6 digits long, separated by any number of special chars (12--654-5, 453/--222, 23....5645 etc) OR no more than 3 chars (ltters) (06asd453, 123as562).
Thank you again, all answers are vry helpfull, but i am gulty because i didnt formulated my question right.
p.s. i cant give u reputation because i must have at least 15, as soon as i get that much, i will 'vote up', all answers deserve it.
Hmm why so complicated when you only want to mascarade your string.
$input = '0654535263';
$input = substr($input, 0, 2);
$output = $input . '********';
Its a bit easier when you only want the first 2 characters of your string. Perhaps your solution had another sin. But this is a bit easier.
You can just use substr_replace
echo substr_replace($v, "****", 2);
Example
$list = array("0654535263","065453-.-5263","065asd4535263");
echo "<pre>";
foreach ( $list as $v ) {
echo substr_replace($v, "****", 2), PHP_EOL;
}
Output
06****
06****
06****
I'm guessing that the reason you want to use regular expressions is so that you don't mask every string that you get. This regex checks that there is at least 2 digits in the beginning of the string, then 0 to 3 alphabet characters, and then all the rest of the characters of the string need to be non-alphabet characters. If it matches, it masks the string, otherwise it says the string does not match.
$string = '0654535263';
if(preg_match('~^(\d{2})\d*?[a-zA-Z]{0,3}[^a-zA-Z]*$~', $string))
$answer = preg_replace('~^(\d{2})\d*?[a-zA-Z]{0,3}[^a-zA-Z]*$~', '$1****', $string);
else
$answer = $string . ' does not match';
print_r($answer); // 06****

Categories