简体   繁体   中英

preg_match does not match regex

I am trying to scrape 10 digit numbers from a website with regex and pregmatch. So far have not been able to get any results. It matches when I use regular characters like in the first two commented out $regex variables. But not when I use regex as in the other ones.

I have checked all other similar questions here. Yet haven't been able to understand why the following regex script outputs empty array like

array(1) { [0]=> array(0) { } }

CODE

<?php 
$data=file_get_contents("http://www.landshoppe.com/contactus");
//$regex = '/9833157945/';
//$regex = "/<a href='(.+?)'>/";
$regex='/^[0-9]\b\d{10}\b$/';

//$regex='/\(?\s?[2-9][0-9]{2}[(\s?\)?\s?)\-\.]{1,3}[0-9]{3}[\s\-\.]{1,3}[0-9]{10}/';
//$regex='/\[^\d\]/';
preg_match_all($regex,$data,$match);
//preg_match_all($regex,"9898989898 kmllkj 9087654567 kjhkhkhj 9043567898 hkhkjhkjhk",$match);
//  var_dump($data);
//  echo htmlspecialchars($data);

var_dump($match); 
echo "<p></p>";
foreach($match as $m){foreach($m as $ma){echo $ma."<br>";}}
//echo $match[1];
?>

If you observe, I have been trying all kinds of regex combinations and none giving result.

Note that this expression: /^[0-9]{5}$/ will match strings which are entirely made up from 5 digits. The ^ and $ instruct the engine to match from the beginning and keep on going until the end. This is different from the expression of /9833157945/ , which denotes a particular 10 digit number.

You would need to change it at least to \\d{10} to match 10 digits. If the digits must not be contained within other strings, that is, foo0123456789 , you could use the \\b tag: \\b\\d{10}\\b .

'/[0-9]\\d{10}/' solved my issue ! It now matches all the 10 digit numbers !

Thanks all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM