I'm new to regex and I am really bad at it.
I've been trying to solve this problem but still can't get the result. So, I'm hoping that someone is able to assist me. thanks!
$str = "/tqrfq_58533_13";
preg_match_all('/\d+(?>=_)*/', $str, $matches);
print_r($matches); // gets 58533, 13
but I only want '58533' and not both numbers. So I want the array of $matches to return '58533' as the only number
Use /(?<=_)(\d+)(?=_)/ as pattern in preg_match() that match digits between _
$str = "/tqrfq_58533_13";
preg_match('/(?<=_)(\d+)(?=_)/', $str, $matches);
echo $matches[0];
// 58533
Check result in demo
Also you can use preg_replace() if you don't want to get array as result
echo preg_replace('/.*?_(\d+)_.*/', "$1", $str);
// 58533
preg_match_all('/\d+(?=_)/', $str, $matches);
If you want to get only one number, remove * part since it means the result will be more than one. AFAIK, there is no such things like (?>=_). I use (?=_) to indicate that _ immediately follow the number.
You can see this link for more clarification.
Related
I have the following string: cache:search:amsterdam:hotel
I want to have a preg_match_all to find the words amsterdam and hotel (in this case). I've done some looking around and came to:
preg_match_all( "/(?<=cache:search)(:/w*)/i", "cache:search:amsterdam:hotel", $matches )
I'm hoping to get $matches to have the values amsterdam and hotel, but so far I was only able to get :amsterdam:hotel or just :amsterdam in various tries. How can I get all words in between the parenthesis after the cache:search?
First, once you have extracted :amsterdam:hotel you can easily split the string.
If you want to directly obtain separated words, you can use a \G based pattern:
preg_match_all('~(?:\G(?!\A)|cache:search):\K[^:]+~', $subject, $matches);
Where \G matches the position immediately after the previous match. (Note that \G matches the start of the string too, that's why I added (?!\A).)
Additionally to guys answers, in case you find it useful you can also use a regex like this:
(\w+):(\w+)$
Regex demo
preg_match_all('~(\w+):(\w+)$~', "cache:search:amsterdam:hotel", $matches);
You can just collect the last two words. This should work:
preg_match_all( "/(\w+):(\w+)$/i", "cache:search:amsterdam:hotel", $matches )
Edit:
In case there are more than two words you want to capture I would recommend explode instead:
$str = 'cache:search:amsterdam:hotel';
$matches = explode(':', substr($str, 13));
A way to do this without a preg_match is this:
$matches = array_splice( ( explode( ':', 'cache:search:amsterdam:hotel' ) ), 2 );
I compared this to the accepted answer (the preg_match_all), that takes 56% longer to execute. The question was a regexp, so that will remain the accepted answer, but I wanted to post this alternative as well for people that come across the same problem
I know this type of questions have been asked before but none solves my problem.
I want to capture numeric parts of this string INFORMATICS&SYSTEMS-58600 i.e. 58600.
I am trying to do substr(INFORMATICS&SYSTEMS-58600,-5) which returns ATICS which is substr of first part of string INFORMATICS but I want the last part.
Wherever & is appearing this is behaving same.
I know its a very basic mistake but what ??? I cant figure out.Please help me out.
$str = 'INFORMATICS&SYSTEMS-58600';
preg_match_all('!\d+!', $str, $matches);
print_r($matches);
Can refer Extract numbers from a string
Actully PHP substr is working fine.
1. I was passing this text as url query in ajax i.e. get_data.php?dept ='informatics& system' so anything after & was treated as second parameter.
I found this nice answer on link to pass ajax parameters in url as encoded.
The regex in this code matches a number at the end of a string.
<?php
$str = "INFORMATICS&SYSTEMS-58600";
$matches = array();
preg_match("/\d+$/", $str, $matches);
foreach($matches as $match) {
echo $match;
}
?>
Output:
58600
I'm a regex-noobie, so sorry for this "simple" question:
I've got an URL like following:
http://stellenanzeige.monster.de/COST-ENGINEER-AUTOMOTIVE-m-w-Job-Mainz-Rheinland-Pfalz-Deutschland-146370543.aspx
what I'm going to archieve is getting the number-sequence (aka Job-ID) right before the ".aspx" with preg_replace.
I've already figured out that the regex for finding it could be
(?!.*-).*(?=\.)
Now preg_replace needs the opposite of that regular expression. How can I archieve that? Also worth mentioning:
The URL can have multiple numbers in it. I only need the sequence right before ".aspx". Also, there could be some php attributes behind the ".aspx" like "&mobile=true"
Thank you for your answers!
You can use:
$re = '/[^-.]+(?=\.aspx)/i';
preg_match($re, $input, $matches);
//=> 146370543
This will match text not a hyphen and not a dot and that is followed by .aspx using a lookahead (?=\.aspx).
RegEx Demo
You can just use preg_match (you don't need preg_replace, as you don't want to change the original string) and capture the number before the .aspx, which is always at the end, so the simplest way, I could think of is:
<?php
$string = "http://stellenanzeige.monster.de/COST-ENGINEER-AUTOMOTIVE-m-w-Job-Mainz-Rheinland-Pfalz-Deutschland-146370543.aspx";
$regex = '/([0-9]+)\.aspx$/';
preg_match($regex, $string, $results);
print $results[1];
?>
A short explanation:
$result contains an array of results; as the whole string, that is searched for is the complete regex, the first element contains this match, so it would be 146370543.aspx in this example. The second element contains the group captured by using the parentheeses around [0-9]+.
You can get the opposite by using this regex:
(\D*)\d+(.*)
Working demo
MATCH 1
1. [0-100] `http://stellenanzeige.monster.de/COST-ENGINEER-AUTOMOTIVE-m-w-Job-Mainz-Rheinland-Pfalz-Deutschland-`
2. [109-114] `.aspx`
Even if you just want the number for that url you can use this regex:
(\d+)
Suppose, I am having a string like
$res = "there are many restaurants in the city. Restaurants like xyz,abc. one restaurant like.....";
In the above example, We can find restaurant in 3 places. I need the count to be 3.
$pattern = '/Restaurant/';
preg_match($pattern, substr($res,10), $matches, PREG_OFFSET_CAPTURE);
print_r($matches);
One more problem
Which is related to the above question. i.e., I am having text like Food & Drinks. I need to match this word with food or drinks or seafood... etc. can anyone please help me in getting this. Thanks in advance.
You can use a regex like this:
$pattern = '/restaurants?/i';
There are two changes that I made to your original regex:
Adding the i modifier - this is the case insensitive flag.
Adding s? to the end of the search string. This makes the last s character optional. It matches zero or one occurances of s.
Note that because we are using the case insensitive flag, this regex will also match things like :
ResTaurants
rEstaurantS
RESTauRANTS
The i modifier is used for case-insensitive matching. The ? quantifier makes the preceding token optional matching in this case the preceding s either zero or one time.
You are using preg_match() wanting to get all matches, you need preg_match_all()
$pattern = '/restaurants?/i';
preg_match_all($pattern, substr($res,10), $matches, PREG_OFFSET_CAPTURE);
print_r($matches[0]);
See working demo
I suggest looking at a regex guide - this is a very simple request.
| in regex means or and ? means 0 or 1 of previous char or group, so the following pattern should work for your specification:
$pattern = '/[Rr]estaurants?/
As a solution to your problem please try executing following code snippet
$url = "http://www.examplesite.com/";
$curl = new Curl();
$res = $curl->get($url);
$pattern = '/Restaurant(s)*/i';
preg_match($pattern, substr($res,10), $matches, PREG_OFFSET_CAPTURE);
print_r($matches);
for example i have data response from here:
http://www.facebook.com/ajax/shares/view/?target_fbid=410558838979218&__a=1
there is a pattern that looks like this:
data-hovercard=\"\/ajax\/hovercard\/hovercard.php?id=655581307\">
how can i parse it with the preg_match_all() in PHP?
I know i need complex regular expression, but i dont have a clue how to write one for such pattern in the text.
Thanks for help
UPD:
the following code does give the id:
$str = 'hovercard.php?id=655581307';
preg_match_all('/[0-9]{9}/', $str , $matches);
print_r($matches);
BUT
this one doesnt
$url = 'http://www.facebook.com/ajax/shares/view/?target_fbid=410558838979218&__a=1';
$html = file_get_contents($url);
preg_match_all('/[0-9]{9}/', $html, $matches);
print_r($matches);
This gets a bit messy due to the backslashes escaping stuff, but to match exactly that string this call to preg_match_all() should work:
preg_match_all('#(data-hovercard=\\\\"\\\\/ajax\\\\/hovercard\\\\/hovercard.php\?id=[0-9]+\\\\">)#', $str, $matches);
That will give you the whole string you posted in $matches. However, if you only want the numbers from id you can add extra parenthesis around that like so:
preg_match_all('#(data-hovercard=\\\\"\\\\/ajax\\\\/hovercard\\\\/hovercard.php\?id=([0-9]+)\\\\">)#', $str, $matches);
And the numbers will appear individually in $matches (similarly, you can remove the parenthesis that wraps the whole regexp to stop matching the whole string).
Update:
And now I see the question is updated. If your new example fails it's because there are no sequence of 9 digits in the data you get. When I try myself I simply get a response that says I need to log in, so maybe your matching issues is in fact due to you not getting the data you expect? Try dumping $html to see if what you are looking for is in fact in there.