Regex For Get Last URL - php

I have:
stackoverflow.com/.../link/Eee_666/9_uUU/66_99U
What regex for /Eee_666/9_uUU/66_99U?
Eee_666, 9_uUU, and 66_99U is a random value
How can I solve it?

As simple as that:
$link = "stackoverflow.com/.../link/Eee_666/9_uUU/66_99U";
$regex = '~link/([^/]+)/([^/]+)/([^/]+)~';
# captures anything that is not a / in three different groups
preg_match_all($regex, $link, $matches);
print_r($matches);
Be aware though that it eats up any character expect the / (including newlines), so you either want to exclude other characters as well or feed the engine only strings with your format.
See a demo on regex101.com.

You can use \K here to makei more thorough.
stackoverflow\.com/.*?/link/\K([^/\s]+)/([^/\s]+)/([^/\s]+)
See demo.
https://regex101.com/r/jC8mZ4/2

In the case you don't how the length of the String:
$string = stackoverflow.com/.../link/Eee_666/9_uUU/66_99U
$regexp = ([^\/]+$)
result:
group1 = 66_99U
be careful it may also capture the end line caracter

For this kind of requirement, it's simpler to use preg_split combined with array_slice:
$url = 'stackoverflow.com/.../link/Eee_666/9_uUU/66_99U';
$elem = array_slice(preg_split('~/~', $url), -3);
print_r($elem);
Output:
Array
(
[0] => Eee_666
[1] => 9_uUU
[2] => 66_99U
)

Related

get variables from regular expresion

I have one of the following strings:
mystring
/mystring
mystring?test
/mystring?test
That is one string preceded by one optional / and followed by and optional ?test
I need to get this variables:
$string = "mystring"
$test = false / true depending if ?test is present
I'm trying to use regular expressions but I'm having trouble with the right pattern. I'm trying:
\/?(\w+)(\??\w+)
For example, for "mystring", I'm getting this:
Array
(
[0] => /mystring
[1] => mystrin
[2] => g
)
This is a sample code:
<?
echo "<pre>";
$input = "/mystring";
$pattern = "/\/?(\w+)(\??\w+)/";
$matches = null;
preg_match($pattern, $input, $matches);
print_r($matches);
?>
For a non-regex alternative if you're interested, you can use parse_url. It accepts partial URLs, and it can parse strings like those.
$components = parse_url($input);
$string is the path with leading slash removed, and $test is the equality of the query to the string 'test'.
$string = trim($components['path'], '/');
$test = isset($components['query']) && $components['query'] == 'test';
You're including the ? in catch expression.
The regex you should use: \/?(\w+)\??(\w+)?
This will use less number of steps (46 compared to 56 of your regex) hence less load on the server too.
Demo: https://regex101.com/r/98QNeh/2

Get numbers after string php regex

I need a regex that can actually get any number that is inserted after "ab" and "cr". For example, I have a string like this:
rw200-208-ab66
fg200-cr30-201
I need to print ab66 and cr30.
I have tried using strpos:
if (strpos($part,'ab') !== false) {
$a = explode("ab", $part);
echo 'ab'.$a[1];
}
That does not work for the second item.
You could use \K to discard the previously matched chars from printing at the final. The below regex would give you the number which exists next to ab
or cr.
(?:ab|cr)\K\d+
To get the number with alphabets also, use
preg_match_all('~(?:ab|cr)\d+~', $str, $match);
Use this regex:
(?>ab|cr)\d+
See IDEONE demo:
$re = "#(?>ab|cr)\d+#";
$str = "rw200-208-ab66\nfg200-cr30-201";
preg_match_all($re, $str, $matches);
print_r($matches[0]);
Output:
Array
(
[0] => ab66
[1] => cr30
)

Remove the end of a string with a varying string length using PHP

Using PHP I have an array that return this data for an image:
Array
(
[0] => http://website.dev/2014/05/my-file-name-here-710x557.png
[1] => 710
[2] => 557
[3] => 1
)
Based on the demo data above, I need to somehow turn this image URL into:
http://website.dev/2014/05/my-file-name-here.png removing the -710x557 from the string.
Some things to keep in mind are:
The file extension can change and be any type of file type
710x557 might not ALWAYS be a 3 digit x 3 digit number. It could be 2 or 4
The reason I mention this is to show I cannot simply use PHP's string functions to remove the last 12 characters in the string and then add the file extension back because the last string characters could possibly be between 10 and 14 characters long sometimes and not always 12.
I was hoping to avoid a heavy regular expression code but if that is the only or best way here then I say go with it.
How do I write a regex that removes the end of a string that could have a varying length in PHP?
You can use a regex like this:
-\d+x\d+(\.\w+)$
Working demo
The code you can use is:
$re = "/-\\d+x\\d+(\\.\\w+)$/";
$str = "http://website.dev/2014/05/my-file-name-here-710x557.png";
$subst = '\1';
$result = preg_replace($re, $subst, $str, 1);
The idea is to match the resolution -NumbersXNumbers using -\d+x\d+ (that we'll get rid of it) and then capture the file extension by using (\.\w+)$ using capturing group. Check the substitution section above.
As long as it is 2 sets of digits with an 'x' in the middle preceded by a dash you can use this regex:
-[\d]*x[\d]*
$string = 'http://website.dev/2014/05/my-file-name-here-710x557.png';
$pattern = '/-[\d]*x[\d]*/';
$replacement = '';
echo preg_replace($pattern, $replacement, $string);
http://phpfiddle.org/lite/code/eh40-6d1x
You can probably use strrpos in the following manner to do this:
$str = substr($str, 0, strrpos($str, '-')) . substr($str, strrpos($str, '.'));
You can use this regex based code:
$str = "http://website.dev/2014/05/my-file-name-here-710x557.png";
$re = '/-([^-]+)(?=\.[^-]*$)/';
$result = preg_replace($re, '', $str, 1);
//=> http://website.dev/2014/05/my-file-name-here.png
RegEx Demo
$newsrc = preg_replace('#\-\d+x\d+(\.\w+$)#', '$1', $arr[0]);
see http://ideone.com/ZsELQ0

regex not matching pattern correctly

The data looks like this
cityID=123456789&sharing=blahblahblah
Currently doing
$cityID = preg_grep("/cityID=.\d\&$/", $sometext);
print_r($cityID);
Currently printing
array(
)
I want it to print
123456789
The problem is that $ is marking the end of line, where as this pattern isn't necessarily at the end of a line. Also \d is not allowing for more than one digit before the ampersand, so I added a +. (Also, be aware that . matches any character; it's not clear that is what you want, which is why I asked above.)
This should match for you:
preg_match("/cityID=\d+&/", $input_line, $output_array);
To experiment more with this pattern, visit http://www.phpliveregex.com/p/1WH
You could use preg_match_all()
$str = "cityID=123456789&sharing=blahblahblahcityID=123456789&sharing=blahblahblahcityID=123456789&sharing=blahblahblah";
// or
// $str = "cityID=123456789&sharing=blahblahblah
// cityID=123456789&sharing=blahblahblah
// cityID=123456789&sharing=blahblahblah";
$result = preg_match_all("/cityID=(\d+)/", $str, $matches);
print_r($matches[1]);
Ouput:
Array ( [0] => 123456789 [1] => 123456789 [2] => 123456789 )

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