Getting the value from url which is between the forward slashes. Like
http://localhost/test/manage-users/1230/
output: 1230
I also found some help full answers but they are not satisfy my case properly. Their url is hard coded i.e, their url cant change but in my case url change if user redirect from different pages.
Get the value of a URL after the last slash
Different url when user redirect from different pages.
http://localhost/test/manage-users/1230/?value=1230
http://localhost/test/manage-users/1230/
http://localhost/test/manage-users/1230/test1/?value=1230
So i want a regex which full fill my all cases.
RegEx you need is
\d+(?=\/)
$re = '/\d+(?=\/)/';
$str = 'http://localhost/test/manage-users/1230/?value=1230';
preg_match($re, $str, $matches);
It is working for all three cases you have mentioned.
Check Demo
I don't know if it is possible or not but i have a suggestion. Use URL rewriting.
Feel free to shape your URL's. For example
http://localhost/test/manage-users.php?value=1230
And a little help from this link:
http://www.addedbytes.com/articles/for-beginners/url-rewriting-for-beginners/
You can make it look like:
http://localhost/test/manage-users/1230/
You could try the below regex to get the number between slashes,
\/(\d+)\/
DEMO
Your php code would be,
<?php
$re = '~\/(\d+)\/~';
$str = 'http://localhost/test/manage-users/1230/?value=1230';
preg_match($re, $str, $matches);
echo $matches[1];
?> // 1230
Related
Argh-- regular expressions make me crazy, I've just spent 20 minutes trying to get this to fly and I'm having no luck. And I know someone here will be able to pop this out in like 2 seconds! :-)
Here's a sample source URL: https://rumble.com/v30sqt-oreo-ice-cream-cake.html
I want to extract the "v30sqt" characters. Actually, I want to extract any characters after "rumble.com/" and before the first dash. It might be alphanumeric, it might be all letters, it might be longer than 6 characters, etc. That's the video ID.
This is for php preg_match.
You can simply use parse_url instead of using regex along with explode and current function like as
$url = "https://rumble.com/v30sqt-oreo-ice-cream-cake.html";
$parsed_arr = explode("-",ltrim(parse_url($url, PHP_URL_PATH),"/"));
echo current($parsed_arr);
or
echo $parsed_arr[0];
Demo
Try this one should work for you :
/(?<=rumble.com\/).*?\b/g
Demo and Explaination
Go for:
<?php
$url = "https://rumble.com/v30sqt-oreo-ice-cream-cake.html";
$regex = '~rumble\.com/(?P<video>[^-]+)~';
if (preg_match($regex, $url, $match)) {
echo $match['video'];
# v30sqt
}
?>
With a demo on ideone.com.
I have a URL regex I use (and have used quite frequently). It does me well for finding various URL formats and http protocols. That said, I wouldn't be writing here if all was dandy in Dandyland.
I've encountered a hiccup that my current regex below is causing.
When searching a string for URLs, if a string consists of something like example...see it will treat it as a URL. There can be any number of periods, however it only pulls the last 3 characters after the last period.
Any ideas how to resolve this?
Example:
$string = "Here's a url, hello.com. But this...shouldn't show.";
$url_regex = "/((https?|ftp)\:\/\/)?([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?#)?([a-z0-9-.]*)\.([a-z]{2,3})(\:[0-9]{2,5})?(\/([a-z0-9+\$_\-~#\(\)\%]\.?)+)*\/?(\?[a-z+&\$_.-][a-z0-9;:#&#%=+\/\$_.-]*)?(#[a-z_.-][a-z0-9+\$_.-]*)?/i";
preg_match_all($url_regex, $string, $urls);
return $urls;
The problem here was that you had added a period within the allowed characters which meant there could be more than one consecutive periods. Also \b is important when you're dealing with inline searches.
\b((https?|ftp)\:\/\/)?([a-z0-9+!*(),;?&=\$_-]+(\:[a-z0-9+!*(),;?&=\$_-]+)?#)?([a-z0-9-]*)\.([a-z]+){2,3}(\:[0-9])?(\/([a-z0-9+\$_\-~#\(\)\%]?)+)*\/?(\?[a-z+&\$_-][a-z0-9;:#&#%=+\/\$_-]*)?(#[a-z_-][a-z0-9+\$_-]*)?\b
Debuggex Demo
Edit: Updated the answer to ignore matches like example.c
Following code solve your issue. I have test at my end.
$string = "Here's a url, hello.com. But this...shouldn't show.";
$url_regex = "/((https?|ftp)\:\/\/)?([a-z0-9+!*(),;?&=\$_.-]+(\:[a-z0-9+!*(),;?&=\$_.-]+)?#)?([a-z0-9-]+?)\.([a-z]{2,3})(\:[0-9]{2,5})?(\/([a-z0-9+\$_\-~#\(\)\%]\.?)+)*\/?(\?[a-z+&\$_.-][a-z0-9;:#&#%=+\/\$_.-]*)?(#[a-z_.-][a-z0-9+\$_.-]*)?/i";
preg_match_all($url_regex, $string, $urls);
Use https and http with urls in the string.
$string = "this is my website http://example.com and this is my friend website https://pqr.com etc, this...shouldn't show";
$regex = '/\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|$!:,.;]*[A-Z0-9+&##\/%=~_|$]/i';
preg_match_all($regex, $string, $matches);
print_r($matches[0]);
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
PHP if string contains URL isolate it
I would like to use some kind of regex to extract any type of links like www.google.com or http://google.com or https://google.com or just google.com from a string
I have used something like this..but it only detects links with http and https
$regex ="/(https?:\/\/[^\s]+)/";
$string ="is there a link http://google.com in this string?";
preg_match($regex, $string,$matches);
print_r($matches);
The output I get is
Array ( [0] => http://google.com)
I want to detect all types of possible links in a string.
Any help will be appreciated!! :)
I replace all URL with hyperlink but you can do whatever you want.
function formatUrlsInText($text)
{
$reg_exUrl = "%^((http|https|ftp|ftps?://)|(www\.))([a-z0-9-].?)+(:[0-9]+)?(/.*)?$%i";
preg_match_all($reg_exUrl, $text, $matches);
$usedPatterns = array();
foreach($matches[0] as $pattern){
if(!array_key_exists($pattern, $usedPatterns)){
$usedPatterns[$pattern]=true;
$text = str_replace ($pattern, "<a href='{$pattern}' rel='nofollow' target='_blank'>{$pattern}</a> ", $text);
}
}
return $text;
}
Just make use of alternations to cover the other patterns. Try something like this:
(https?:\/\/[^\s]+|\bwww\.[^\s]+|[^\s]+\.(?:com|org|uk)\b)
See it here online on Regexr
The first part is yours. The second part will match everything that starts with www. and the third part will match everything that ends with something from this list (com|org|uk). You can add any domain you want to match to this list.
I am quite sure this will match a lot of stuff thats not a valid URL, but if you are happy with your Regex, probably the other two patterns are also fine for your need.
I know I've seen this done a lot in places, but I need something a little more different than the norm. Sadly When I search this anywhere it gets buried in posts about just making the link into an html tag link. I want the PHP function to strip out the "http://" and "https://" from the link as well as anything after the .* so basically what I am looking for is to turn A into B.
A: http://www.youtube.com/watch?v=spsnQWtsUFM
B: www.youtube.com
If it helps, here is my current PHP regex replace function.
ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]", "\\0", htmlspecialchars($body, ENT_QUOTES)));
It would probably also be helpful to say that I have absolutely no understanding in regular expressions. Thanks!
EDIT: When I entered a comment like this blahblah https://www.facebook.com/?sk=ff&ap=1 blah I get html like this<a class="bwl" href="blahblah https://www.facebook.com/?sk=ff&ap=1 blah">www.facebook.com</a> which doesn't work at all as it is taking the text around the link with it. It works great if someone only comments a link however. This is when I changed the function to this
preg_replace("#^(.*)//(.*)/(.*)$#",'<a class="bwl" href="\0">\2</a>', htmlspecialchars($body, ENT_QUOTES));
This is the simples and cleanest way:
$str = 'http://www.youtube.com/watch?v=spsnQWtsUFM';
preg_match("#//(.+?)/#", $str, $matches);
$site_url = $matches[1];
EDIT: I assume that the $str had been checked to be a URL in the first place, so I left that out. Also, I assume that all the URLs will contain either 'http://' or 'https://'. In case the url is formatted like this www.youtube.com/watch?v=spsnQWtsUFM or even youtube.com/watch?v=spsnQWtsUFM, the above regexp won't work!
EDIT2: I'm sorry, I didn't realize that you were trying to replace all strings in a whole test. In that case, this should work the way you want it:
$str = preg_replace('#(\A|[^=\]\'"a-zA-Z0-9])(http[s]?://(.+?)/[^()<>\s]+)#i', '\\1\\3', $str);
I am not a regex whizz either,
^(.*)//(.*)/(.*)$
\2
was what worked for me when I tried to use as find and replace in programmer's notepad.
^(.)// should extract the protocol - referred as \1 in the second line.
(.)/ should extract everything till the first / - referred as \2 in the second line.
(.*)$ captures everything till the end of the string. - referred as \3 in the second line.
Added later
^(.*)( )(.*)//(.*)/(.*)( )(.*)$
\1\2\4 \7
This should be a bit better, but will only replace just 1 URL
The \0 is replaced by the entire matched string, whereas \x (where x is a number other than 0 starting at 1) will be replaced by each subpart of your matched string based on what you wrap in parentheses and the order those groups appear. Your solution is as follows:
ereg_replace("[[:alpha:]]+://([^<>[:space:]]+[:alnum:]*)[[:alnum:]/]", "\\1
I haven't been able to test this though so let me know if it works.
I think this should do it (I haven't tested it):
preg_match('/^http[s]?:\/\/(.+?)\/.*/i', $main_url, $matches);
$final_url = ''.$matches[1].'';
I'm surprised no one remembers PHP's parse_url function:
$url = 'http://www.youtube.com/watch?v=spsnQWtsUFM';
echo parse_url($url, PHP_URL_HOST); // displays "www.youtube.com"
I think you know what to do from there.
$result = preg_replace('%(http[s]?://)(\S+)%', '\2', $subject);
The code with regex does not work completely.
I made this code. It is much more comprehensive, but it works:
See the result here: http://cht.dk/data/php-scripts/inc_functions_links.php
See the source code here: http://cht.dk/data/php-scripts/inc_functions_links.txt
I need to extract the first URL from some content. The content may be like this:
({items:[{url:"http://cincinnati.ebayclassifieds.com/",name:"Cincinnati"},{url:"http://dayton.ebayclassifieds.com/",name:"Dayton"}],error:null});
or may contain only a link
({items:[{url:"http://portlandor.ebayclassifieds.com/",name:"Portland (OR)"}],error:null});
currently I have :
$pattern = "/\:\[\{url\:\"(.*)\"\,name/";
preg_match_all($pattern, $htmlContent, $matches);
$URL = $matches[1][0];
however it works only if there is a single link so I need a regex which should work for the both cases.
You can use this REGEX:
$pattern = "/url\:\"([^\"]+)\"/";
Worked for me :)
Hopefully this should work for you
<?php
$str = '({items:[{url:"http://cincinnati.ebayclassifieds.com/",name:"Cincinnati"},{url:"http://dayton.ebayclassifieds.com/",name:"Dayton"}],error:null});'; //The string you want to extract the 1st URL from
$match = ""; //Define the match variable
preg_match("%(((ht|f)tp(s?))\://)?(www.|[a-zA-Z].)[a-zA-Z0-9\-\.]+\.(com|edu|gov|mil|net|org|biz|info|name|museum|us|ca|uk)(\:[0-9]+)*(/($|[a-zA-Z0-9\.\,\;\?\'\\\+&\%\$#\=~_\-]+))*%",$str,$match); //I Googled for the best Regular expression for URLs and found the one included in the preg_match
echo $match[0]; //Return the first item in the array (the first URL returned)
?>
This is the website that I found the regular expression on: http://regexlib.com/Search.aspx?k=URL
like the others have said, json_decode should work for you aswell
That smells like JSON to me. Try using http://php.net/json_decode
Looks like JSON to me, visit http://php.net/manual/en/book.json.php and use json_decode().