Search a Number pattern - php

I want to search a phone number from a whole sentence. It can be any number with a pattern like (122) 221-2172 or 122-221-2172 or (122)-221-2172 by help of PHP where I don't know in which part of the sentence that number is exists or I could use substr.

$text = 'foofoo 122-221-2172 barbar 122 2212172 foofoo ';
$text .= ' 122 221 2172 barbar 1222212172 foofoo 122-221-2172';
$matches = array();
// returns all results in array $matches
preg_match_all('/[0-9]{3}[\-][0-9]{6}|[0-9]{3}[\s][0-9]{6}|[0-9]{3}[\s][0-9]{3}[\s][0-9]{4}|[0-9]{9}|[0-9]{3}[\-][0-9]{3}[\-][0-9]{4}/', $text, $matches);
$matches = $matches[0];
var_dump($matches);

You can use regular expressions to solve this. Not 100% on php syntax, but I imagine it would look something like:
$pattern = '/^\(?\d{3}\)?-\d{3}-\d{4}/';
^ says "begins with"
\( escapes the (
\(? say 0 or 1 (
\d{x} says exactly x numbers
You may also want to check out Using Regular Expressions with PHP

Related

Change 10.28 by 1028

I have a problem with a string to convert in number. I am not good with this elements !\d+!
I used that but the apporach is not correct.
Thank you.
preg_match_all('!\d+!', $product_price[$i], $matches);
$price_extracted = (float)implode('.', $matches[0]);
$item['normal_price'] = $price_extracted;
if ($item['normal_price'] > 800) ......
I have this result
1 299,99 $ (orginal) is converted in 1.2999 and must be 1299.99
549,99 $ (orginal) is converted in 549.99 and must be 549.99
44,99 $ (orginal) is converted in 44.99 and must be 44.99
The problem with your approach is, that you put the digits that are not separated by anything into an array.
This means that with the first string that you provided, where the thousand dollars is seperated by a whitespace is being registered as one of these matches.
preg_match_all('!\d+!', '1 299,99 $', $matches) -> returns an array as follows:
$matches[0] = 1
$matches[1] = 299
$matches[2] = 99
If you take my approach though and first replace all whitespaces by nothing and then split the numbers into the array...:
preg_match_all('!\d+!', preg_replace('/\s/', '', '1 299,99 $'), $matches) -> returns following array:
$matches[0] = 1299
$matches[1] = 99
after that you can still implode them:
$price_exctracted = (float)implode(".", $matches);
EDIT
A little explanation about preg_replace, preg_match_all and regex:
The regex '!\d+!' (I don't actually know why there would be '!' instead of '/' but if it works...) searches for digits (\d). The "+" refers to "one or more". So the line
preg_match_all('!\d+!', 'someString', $myArray)
could be translated into english as follows:
Find all occurances of digits, be it one or more,
and put these occurances separated into one index of $myArray.
The second regex used in my solution, '/\s/' , is used to search for whitespaces. The "preg_replace"-function is an easy "find and replace" function concluding in:
preg_replace('/\s/', '', 'someString')
translated to english:
Find all occurances of whitespaces and replace them with nothing in 'someString'
For reference:
preg_match_all
preg_replace
regex cheat sheet
Conditions can be checked on:
PHP Live Regex

PHP regular expression to extract date from string

It's nothing that I am with this regular expressions stuff. I don't get the regular expression for my requirement. Here is the string format that I have to split with a regular expression in PHP.
ABCxxxx_ABCDEfghi_YYYYmmddhhmmss.mp4
In this string,
ABC -word(case sensitive)
x -any digit
ABCDEfghi -word(case sensitive)
YYYYmmddhhmmss -timestamp value
.mp4 -word preceded with a dot(.)
All I need is to extract the date from this string.
ie, take YYYYmmdd to a variable.
I know that this is not the way of writing it, but I tried. Here is the attempt:
$s = "ABC0000_ABCDEfghi_20000101223344.mp4";
$regex = "/\ABC[0-9]{4}_ABCDEfghi_&var=[0-9]{8}[0-9]{6}+\.mp4/";
$matches = array();
$s = preg_match($regex, $s, $matches);
print_r($matches[1]);
THE ERROR:
( ! ) Notice: Undefined offset: 1 in D:\wamp\www\Test\regex.php on
line 6 Call Stack Time Memory Function Location 1 0.0000 241296
{main}( ) ..\regex.php:0
I am stuck. Please help me with a solution.
Remove the \ before A
Don't use &var, instead you need to use capturing groups.
$regex = '~ABC[0-9]{4}_ABCDEfghi_([0-9]{8})[0-9]{6}\.mp4~';
Add start ^ and end $ anchors if necessary.
DEMO
$s = "ABC0000_ABCDEfghi_20000101223344.mp4";
$regex = '~^ABC[0-9]{4}_ABCDEfghi_([0-9]{8})[0-9]{6}\.mp4$~';
preg_match($regex, $s, $matches);
print_r($matches[1]);
Output:
20000101
(?<=_)\d+(?=\.mp4)
Simply use this.See demo.
https://regex101.com/r/bW3aR1/4
$re = "/(?<=_)\\d+(?=\\.mp4)/";
$str = "ABC0000_ABCDEfghi_20000101223344.mp4";
preg_match_all($re, $str, $matches);

find a specific word in string php

I have a text in PHP stored in the variable $row. I'd like to find the position of a certain group of words and that's quite easy. What's not so easy is to make my code recognize that the word it has found is exactly the word i'm looking for or a part of a larger word. Is there a way to do it?
Example of what I'd like to obtain
CODE:
$row= "some ugly text of some kind i'd like to find in someway"
$token= "some";
$pos= -1;
$counter= substr_count($row, $token);
for ($h=0; $h<$counter; $h++) {
$pos= strpos($row, $token, $pos+1);
echo $pos.' ';
}
OUTPUT:
what I obtain:
0 17 47
what I'd like to obtain
0 17
Any hint?
Use preg_match_all() with word boundaries (\b):
$search = preg_quote($token, '/');
preg_match_all("/\b$search\b/", $row, $m, PREG_OFFSET_CAPTURE);
Here, the preg_quote() statement is used to correctly escape the user input so as to use it in our regular expression. Some characters have special meaning in regular expression language — without proper escaping, those characters will lose their "special meaning" and your regex might not work as intended.
In the preg_match_all() statement, we are supplying the following regex:
/\b$search\b/
Explanation:
/ - starting delimiter
\b - word boundary. A word boundary, in most regex dialects, is a position between a word character (\w) and a non-word character (\W).
$search - escaped search term
\b - word boundary
/ - ending delimiter
In simple English, it means: find all the occurrences of the given word some.
Note that we're also using PREG_OFFSET_CAPTURE flag here. If this flag is passed, for every occurring match the appendant string offset will also be returned. See the documentation for more information.
To obtain the results you want, you can simply loop through the $m array and extract the offsets:
$result = implode(' ', array_map(function($arr) {
return $arr[1];
}, $m[0]));
echo $result;
Output:
0 18
Demo
What you're looking for is a combination of Regex with a word boundaries pattern and the flag to return the offset (PREG_OFFSET_CAPTURE).
PREG_OFFSET_CAPTURE
If this flag is passed, for every occurring match the appendant
string offset will also be returned. Note that this changes the
value of matches into an array where every element is an array
consisting of the matched string at offset 0 and its string offset
into subject at offset 1.
$row= "some ugly text of some kind i'd like to find in someway";
$pattern= "/\bsome\b/i";
preg_match_all($pattern, $row, $matches, PREG_OFFSET_CAPTURE);
And we get something like this:
Array
(
[0] => Array
(
[0] => Array
(
[0] => some
[1] => 0
)
[1] => Array
(
[0] => some
[1] => 18
)
)
)
And just loop through the matches and extract the offset where the needle was found in the haystack.
// store the positions of the match
$offsets = array();
foreach($matches[0] as $match) {
$offsets[] = $match[1];
}
// display the offsets
echo implode(' ', $offsets);
Use preg_match():
if(preg_match("/some/", $row))
// [..]
The first argument is a regex, which can match virtually anything you want to match. But, there are dire warnings about using it to match things like HTML.

Extract substring from array of strpos values

I have the following string
$string = "Hello World!<br />- 8/7/2013<br />Content<br />- 8/6/2013<br />Hello World";
I want to extract all the information between the dash + space ("- ") and the next line break tag. Is that possible? I've been researching Google for hours but no luck. I'm thinking that I need an array of strpos of the "- " and the following line break tag and then batch substr them. But of course if you can do this any other way, that would be so much appreciated!
I've updated my answer to handle multiple occurances.
You can do this with a simple regular expression:
preg_match_all("#- (.*)<br />#U", $string, $matches);
print_r($matches[1]);
The above will print
Array
(
[0] => 8/7/2013
[1] => 8/6/2013
)
This matches the pattern - (.*)<br /> with (.*) meaning anything. The #s here work as delimiters to separate the actual pattern with the modifiers (in this case U meaning an ungreedy match).
regular expressions will give you the most control, but here is a quick demo using strpos and substr to get what you asked for:
$strStart = strpos($string, '- ');
$strLength = strpos($string, '<br') - $strStart;
substr( $string, $strStart, $strLength );

Regex to split alphanumeric, currency and numeric terms in PHP

I am trying to split a string into terms in PHP using preg_split. I need to extract normal words ( \w ) but also currency ( even currency symbol ) and numeric terms ( including commas and decimal points ). Can anyone help me out, as I cannot seem to create a valid regex to use for preg_split to achieve this. Thanks
Why not use preg_match_all() instead of preg_split() ?
$str = '"1.545" "$143" "$13.43" "1.5b" "hello" "G9"'
. ' This is a test sentence, with some. 123. numbers'
. ' 456.78 and punctuation! signs.';
$digitsPattern = '\$?\d+(\.\d+)?';
$wordsPattern = '[[:alnum:]]+';
preg_match_all('/('.$digitsPattern.'|'.$wordsPattern.')/i', $str, $matches);
print_r($matches[0]);
What about preg_match_all() each word with this [\S]+\b then you get an array with the words in it.
Big brown fox - $20.25 will return
preg_match_all('/[\S]+\b/', $str, $matches);
$matches = array(
[0] = 'Big',
[1] = 'brown',
[2] = 'fox',
[3] = '$20.25'
)
Does it solve your problem to split on whitespace? "/\s+/"

Categories