Regex to get string from last numeric values - php

I have some php string like below
abc-1987-mp3-songs
xyz-1999-india-mp3-songs
dec-2001-mp3-songs
ryu-2012-freemp3-songs
Now I want these string splited at last found numeric values like below
abc-1987
xyz-1999
dec-2001
ryu-2012
Please help me that which regex can be used to do this. thanks.

Ok, I had a look (do take some time to learn regex - but meanwhile):
$split = (preg_split('/(^.*?[0-9]+)\-?[^0-9]+/', 'foo-xyz-1999-india-mp3-songs', -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY));
echo $split[0];//<--- foo-xyz-1999, just like you wanted
Dumps an array with foo-xyz-1999 as first value, which is what you need. If you want to know what every part of the regex does read it here
The only difference is that, though the whole string becomes its own delimiter, there are two delimiters (the first part, always ending on a series of numbers and the rest of the string, that doesn't contain any more digits)

Use explode insted of regular expression
for example:-
$str="abc-1987-mp3-songs";
$f=explode("-",$str);
echo $final_result=$f[0]."-".$f[1];
or if you want to use reg exp.then
<?php
$str="abc-1987-mp3-songs";
echo $f=preg_replace('/[^0-9]/','', $str);
?>
Above code give you all the numeric digits of your string.

This would match last occurrence of numeric value from given string:
([\w\d-]*-[\d]+)
This is the link: Regex

Related

PHP regular expression with nth occurrence

Here's a string:
n%3A171717%2Cn%3A%747474%2Cn%3A555666%2Cn%3A1234567&bbn=555666
From this string how can I extract 1234567 ? Need a good logic / syntax.
I guess preg_match would be a better option than explode function in PHP.
It's about a PHP script that extracts data. The numbers can vary and the occurrence of numbers can vary as well only %2Cn%3A will always be there in front of the numbers.the end will always have a &bbn=anyNumber.
That looks like part of an encoded URL so there's bound to be better ways to do it, but urldecoded() your string looks like:
n:171717,n:t7474,n:555666,n:1234567&bbn=555666
So:
preg_match_all('/n:(\d+)/', urldecode($string), $matches);
echo array_pop($matches[1]);
Parenthesized matches are in $matches[1] so just array_pop() to get the last element.
If &bbn= can be anywhere (except for at the beginning) then:
preg_match('/n:(\d+)&bbn=/', urldecode($string), $matches);
echo $matches[1];
only %2Cn%3A will always be there in front of the numbers
urldecoded equivalent of %2Cn%3A is ,n:.The last "enclosing boundary" &bbn remains as is.
preg_match function will do the job:
preg_match("/(?<=,n:)\d+(?=&bbn)/", urldecode("n%3A171717%2Cn%3A%747474%2Cn%3A555666%2Cn%3A1234567&bbn=555666"), $m);
print_r($m[0]); // "1234567"

Get specific string content inside big string

I have a big string like this:
[/az_column_text][/vc_column_inner][vc_column_inner width="3/4"]
[az_latest_posts post_layout="listed-layout" post_columns_count="2clm" post_categories="assemblea-soci-2015"]
[/vc_column_inner][/vc_row_inner][/vc_column]
What I need to extract:
assemblea-soci-2015
Of course this value can change, and also the big string can change too. I need a regex or something else to extract this value (it will be always from post_categories="my-value-to-extract") from this big string.
I think to take post_categories=" as the beginning of a possible substring and the next char " as the end of my portion, but no idea how to do this.
Is there an elegant way to do this also for future values with, of course, different length?
You can use this regex in PHP:
post_categories="\K[^"]+
RegEx Demo
You can use this regex:
(?<=post_categories=")[^"]+(?=")
?<= (lookbehind) looks for post_categories=" before the desired match, and (?=) (lookahead) looks for " after the desired match.
[^"] gets the match (which is assumed not to contain any ")
Demo
Example PHP code:
$text='[/az_column_text][/vc_column_inner][vc_column_inner width="3/4"]
[az_latest_posts post_layout="listed-layout" post_columns_count="2clm" post_categories="assemblea-soci-2015"]
[/vc_column_inner][/vc_row_inner][/vc_column]';
preg_match ("/(?<=post_categories=\")[^\"]+(?=\")/", $text,$matches);
echo $matches[0];
Output:
assemblea-soci-2015
This should extract what you want.
preg_match ("/post_categories=\"(.*)\"\[\]/", $text_you_want_to_use)

preg_replace with Regex - find number-sequence in URL

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+)

regex to get date yyyy-mm-dd from any string

first of all excuse me for not being regex familiar that much.What I Would like is a regex that will extract a date like mysql date from any type of string.
Until now I was using this : ^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$
However now I want to extract date patterns from other strings and datetime strings I tried altering the regex to ^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1]). based on some online regex testers, but it fails. Also some times it gave me a result with a 3 digit day.
In other words sting starts with, yyyy-mm-dd and is followed up by spaces characters numbers or anything. How do I extract the date?
UPDATE
I'm testing regex with preg_match here: http://www.pagecolumn.com/tool/pregtest.htm
so far the only thing that seems to work is
[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])
If your string has more than one date form value occurrence and you wanna capture all of them you should use preg_match_all function and if it's not preg_match is enough. Also using ^ and $ means input string is should be just a date, so avoid it.
<?php
$input_string = "yes today is 2013-10-24";
if(preg_match("/\d{4}-\d{2}-\d{2}/", $input_string, $match))
{
print_r($match);
}
else
echo "not matched";
////////////////////////
/* Output:
Array
(
[0] => 2013-10-24
)
*/
Live demo
Try this:
you can use preg_match() or preg_match_all()
$dateArray = preg_match("/(\d{4}-\d{2}-\d{2})/", $str, $match);
Then use strtotime and date
$date = date('Y-m-d',strtotime($match[0]));
To match dates wherever they appear, remove the $ and ^ anchors from your original regex.
To match dates at the start of any input remove the $ at the end (leave the ^).
You can also put the remaining pattern inside parentheses for convenience, so that the match is also captured as a whole.
Your suggested improvement has a spurious dot at the end which will match any character; that was the reason for returning matches with three-digit days.
Just replace ^ for \b.
\b(\d{4}-\d{2}-\d{2})
It is dot in the end of your regexp (it matches any character, except for line breaks)
Try removing it
^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])

php regex matching first and last

i'm new to regular expressions and would like to match the first and last occurrences of a term in php. for instance in this line:
"charlie, mary,bob,bob,mary, charlie, charlie, mary,bob,bob,mary,charlie"
i would like to just access the first and last "charlie", but not the two in the middle. how would i just match on the first and last occurrence of a term?
thanks
If you know what substring you're looking for (ie. it's not a regex pattern), and you're just looking for the positions of your substrings, you could just simply use these:
strpos — Find position of first occurrence of a string
strrpos — Find position of last occurrence of a char in a string
Try this regular expression:
^(\w+),.*\1
The greedy * quantifier will take care that the string between the first word (\w+) and another occurrence of that word (\1, match of the first grouping) is as large as possible.
You need to add ^ and $ symbols to your regular expression.
^ - matches start of the string
$ - matches end of the string
In your case it will be ^charlie to match first sample and charlie$ to match last sample. Or if you want to match both then it will be ^charlie|charlie$.
See also Start of String and End of String Anchors for more details about these symbols.
Try exploding the string.
$names = "charlie, mary,bob,bob,mary, charlie, charlie, mary,bob,bob,mary,charlie";
$names_array = explode(",", $names);
After doing this, you've got an array with the names. You want the last, so it will be at position 0.
$first = $names_array[0];
It gets a little trickier with the last. You have to know how many names you have [count()] and then, since the array starts counting from 0, you'll have to substract one.
$last = $names_array[count($names_array)-1];
I know it may not be the best answer possible, nor the most effective, but I think it's how you really start getting programming, by solving smaller problems.
Good luck.

Categories