Reputation: 14990
I want to match everything after a specific part of an url, and I cannot get this regEx to work:
$url = 'http://mywebsite.online/noticia/mi-noticia-copada';
$regexPattern = '/^online(.*?)/';
preg_match($regexPattern, $eliminar, $matches);
I get an empty array in $matches.
I have this string:
And I want to get ths:
noticia/mi-noticia-copada
I have this other example string:
And I want to get ths:
mi-otra-noticia-copada
So far the examples that I've read about won't work.
Upvotes: 0
Views: 100
Reputation: 27743
This expression might return the desired output:
^https?:\/\/(?:www\.)?(?:[\w]+\.[\w]+)*\/(.*)$
If you wish to explore/simplify/modify the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.
$re = '/^https?:\/\/(?:www\.)?(?:[\w]+\.[\w]+)*\/(.*)$/m';
$str = 'http://mywebsite.online/noticia/mi-noticia-copada
http://mywebsite.online/mi-otra-noticia-copada
http://mywebsite.onlinem.ywebsite.online/noticia/mi-noticia-copada
http://mywebsite.online/mi-otra-noticia-copada
https://www.mywebsite.online/mi-otra-noticia-copada';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
var_dump($matches);
Upvotes: 1
Reputation: 147216
Your problem is that you've anchored your regex to the start of string by using ^
, so it will only match strings that start with online
. You can change your regex to match .online
as the end of the domain name instead:
$url = 'http://mywebsite.online/noticia/mi-noticia-copada';
$regexPattern = '#^https?://[^/]+\.online/(.*)$#';
preg_match($regexPattern, $url, $matches);
echo $matches[1] . PHP_EOL;
$url = 'http://mywebsite.online/mi-otra-noticia-copada';
preg_match($regexPattern, $url, $matches);
echo $matches[1];
Output:
noticia/mi-noticia-copada
mi-otra-noticia-copada
Upvotes: 2