I know this question has been asked many times on SO, but I can't seem to get this to work.
I'm trying to use regular expressions to find matches for any Facebook URL, but not when the URL contains "plugins/like" (as in "http://www.facebook.com/plugins/like")
I've come out with the following, and I'm not quite sure why it is not working:
https?://(www)?\.facebook\.[a-zA-Z]{2,4}/((?!plugins/like).)
Am I making a very obvious mistake? Sorry if it doesn't make sense at all, but I've only trying a hand at PHP for the past five months.
Thank you very much for your time and your help.
Edit:
I'm getting matches for any FB URL so far, but it isn't excluding anything that contains plugins/like
$urls = array(
'http://www.facebook.com/',
'https://facebook.com/plugins/foo',
'http://facebook.ru/plugins/like',
);
$pattern = '#^https?://(www\.)?facebook\.[a-z]{2,4}/(?!plugins/like)#';
foreach ($urls as $url) {
echo preg_match($pattern, $url) . PHP_EOL;
}
Okay?
here is a solution using strpos()
$url = 'http://www.facebook.com/test/plugins/like?somestuff';
$matches = array();
if(preg_match('#^https?://(?:www)?\.facebook\.[a-zA-Z]{2,4}/(.*)$#', $url, $matches)
&& strpos($matches[1], "plugins/like") === false) {
// ok
} else {
// nope
}
You forgot to esacpe special characters in the pattern. Characters like : and / must be following a backslash.
https?\:\/\/(www)?\.facebook\.[a-zA-Z]{2,4}\/((?!plugins\/like).)
All is ok with your re (and it works; I've checked). The only thing I would change is write
(?!.*plugins/like)
instead of (?!plugins/like).. That is for cases when plugins goes not direct after the facebook.com/.
Related
My url like this:
http://mywebsite.com/movies/937-lan-kwai-fong-2?file=Rae-Ingram&q=
http://mywebsite.com/movies/937-big-daddy?file=something&q=
I want to get "lan-kwai-fong-2" and "big-daddy", so I use this code but it doesn't work. Please help me fix it ! If you can shorten it, it is so great !
$url= $_SERVER['REQUEST_URI'];
preg_replace('/\?file.*/','',$url);
preg_match('/[a-z][\w\-]+$/',$url,$matches);
$matches= str_replace("-"," ",$matches[0]);
First there are issue with your code which im going to go over because they are general things:
preg_replace does not work by reference so you are never actually modifying the url. You need to assign the result of the replace to a variable:
// this would ovewrite the current value of url with the replaced value
$url = preg_replace('/\?file.*/','',$url);
It is possible that preg_match will not find anything so you need to test the result
// it should also be noted that sometimes you may need a more exact test here
// because it can return false (if theres an error) or 0 (if there is no match)
if (preg_match('/[a-z][\w\-]+$/',$url,$matches)) {
// do stuff
}
Now with that out of the way you are making this more difficult than it needs to be. There are specific function for working with urls parse_url and parse_str.
You can use these to easily work with the information:
$urlInfo = parse_url($_SERVER['REQUEST_URI']);
$movie = basename($urlInfo['path']); // yields 937-the-movie-title
Just replace
preg_replace('/\?file.*/','',$url);
with
$url= preg_replace('/\?file.*/','',$url);
Regex works, and parse_url is the right way to do it. But for something quick and dirty I would usually use explode. I think it's clearer.
#list($path, $query) = explode("?", $url, 2); // separate path from query
$match = array_pop(explode("/", $path)); // get last part of path
How about this:
$url = $_SERVER['REQUEST_URI'];
preg_match('/\/[^-]+-([^?]+)\?/', $url, $matches);
$str = isset($matches[1]) ? $matches[1] : false;`
match last '/'
match anything besides '-' until '-'
capture anything besides '?' until (not including) '?'
I know it may sound as a common question but I have difficulty understanding this process.
So I have this string:
http://domain.com/campaign/tgadv?redirect
And I need to get only the word "tgadv". But I don't know that the word is "tgadv", it could be whatever.
Also the url itself may change and become:
http://domain.com/campaign/tgadv
or
http://domain.com/campaign/tgadv/
So what I need is to create a function that will get whatever word is after campaign and before any other particular character. That's the logic..
The only certain thing is that the word will come after the word campaign/ and that any other character that will be after the word we are searching is a special one ( i.e. / or ? )
I tried understanding preg_match but really cannot get any good result from it..
Any help would be highly appreciated!
I would not use a regex for that. I would use parse_url and basename:
$bits = parse_url('http://domain.com/campaign/tgadv?redirect');
$filename = basename($bits['path']);
echo $filename;
However, if want a regex solution, use something like this:
$pattern = '~(.*)/(.*)(\?.*)~';
preg_match($pattern, 'http://domain.com/campaign/tgadv?redirect', $matches);
$filename = $matches[2];
echo $filename;
Actually, preg_match sounds like the perfect solution to this problem. I assume you are having problems with the regex?
Try something like this:
<?php
$url = "http://domain.com/campaign/tgadv/";
$pattern = "#campaign/([^/\?]+)#";
preg_match($pattern, $url, $matches);
// $matches[1] will contain tgadv.
$path = "http://domain.com/campaign/tgadv?redirect";
$url_parts = parse_url($path);
$tgadv = strrchr($url_parts['path'], '/');
You don't really need a regex to accomplish this. You can do it using stripos() and substr().
For example:
$str = '....Your string...';
$offset = stripos($str, 'campaign/');
if ( $offset === false ){
//error, end of h4 tag wasn't found
}
$offset += strlen('campaign/');
$newStr = substr($str, $offset);
At this point $newStr will have all the text after 'campaign/'.
You then just need to use a similar process to find the special character position and use substr() to strip the string you want out.
You can also just use the good old string functions in this case, no need to involve regexps.
First find the string /campaign/, then take the substring with everything after it (tgadv/asd/whatever/?redirect), then find the next / or ? after the start of the string, and everything in between will be what you need (tgadv).
I need some PHP help with strings.
I have a textbox field where users will enter a facebook profile link.
Example: http://facebook.com/zuck
Now the problem is I need to have EXACTLY this string: "http://graph.facebook.com/zuck".
Inputs could be anything like:
http://facebook.com/zuck
http://www.facebook.com/zuck
www.facebook.com/zuck
facebook.com/zuck
What's the best way to do that? Thank you in advance.
To accept anything in the format of facebook.com/username where username is alphanumeric with dots, dashes, and underscores (not sure what Facebook allows exactly):
if (preg_match('%facebook.com/([a-z0-9._-]+)%i', $input, $m))
{
echo 'http://graph.facebook.com/', $m[1], "\n";
}
Why don't you just ask the user for their username? Instead of accepting a wide variety of input, design the form so that they only have to put in their username.
Something along the lines of this;
This way, you don't even have to validate or store anything other than their username. This could be super helpful down the road when Facebook moves fast and breaks stuff, like the URLs of users. Or if you want to form URLs for something other than graph API, you won't have to pull apart an existing URL.
If given inputs will be always as the ones you give i think that strstr function would hadle this
$array = array('http://facebook.com/zuck', 'http://www.facebook.com/buck', 'www.facebook.com/luck', 'facebook.com/nuck');
foreach($array as $data)
{
if(strstr($data, 'facebook.com/'))
{
echo 'http://graph.'.strstr($data, 'facebook.com/') . '<br>';
}
}
This will output
http://graph.facebook.com/zuck
http://graph.facebook.com/buck
http://graph.facebook.com/luck
http://graph.facebook.com/nuck
Find the last slash in the input
$lastpos = strrchr ( $input , '/' )
Manually concatenate the url and everything after that last slash.
$new_url = 'http://www.facebook.com' . substr($input, $lastpos);
$url = 'http://facebook.com/zuck';
$array = explode('/', str_replace('http://', '', $url));
$username = $array[1];
$finalurl = 'http://graph.facebook.com/zuck'.$username;
echo $finalurl;
This will work with any format of input URL.
Something along the lines of:
Pattern:
(https?://)?(www\.)?(.+?)\/([^/]+)
Replace with:
http://graph.$3/$4
Test it here:
http://www.regexe.com/
I have a string which i want to check with a regex. It is not allowed for it to start with a 0. So please see the following examples:
012344 = invalid
3435545645 = valid
021 = invalid
344545 = valid
etc.
How does this regex look in PHP?
PS. This must be a regex solution!
The REGEX should looks like that :
^[1-9][0-9]*$
PHP Code :
<?php
$regex = "#^[1-9][0-9]*$#";
function test($value, $regex)
{
$text = "invalid";
if(preg_match($regex, $value)) $text = "valid";
return $value+" = "+$text+"\n\r";
}
echo test('012345', $regex);
echo test('12345', $regex);
?>
Well it would be a simple /[1-9][0-9]*/.
Please research your question better next time.
This could have also helped you: Regular expression tester
Edit:
Yeah, the answer got downvoted, because it's missing the anchors and seems to be wrong. For completess' sake, I posted the php code I would use with this regex. And no it's not wrong. It may not be the most elegant way, but I like checking whether the regex matched the whole string afterwards more. One reason is that to debug a regex and see what it actually matched I just have to comment out === $value after return $matches[0]
<?php
function matches($value) {
preg_match("/[1-9][0-9]*/", $value, $matches);
return $matches[0] === $value;
}
//Usage:
if (matches("1234")) {
//...
}
?>
I have a input form field which collects mixed strings.
Determine if a posted string contains an URL (e.g. http://link.com, link.com, www.link.com, etc) so it can then be anchored properly as needed.
An example of this would be something as micro blogging functionality where processing script will anchor anything with a link. Other sample could be this same post where 'http://link.com' got anchored automatically.
I believe I should approach this on display and not on input. How could I go about it?
You can use regular expressions to call a function on every match in PHP. You can for example use something like this:
<?php
function makeLink($match) {
// Parse link.
$substr = substr($match, 0, 6);
if ($substr != 'http:/' && $substr != 'https:' && $substr != 'ftp://' && $substr != 'news:/' && $substr != 'file:/') {
$url = 'http://' . $match;
} else {
$url = $match;
}
return '' . $match . '';
}
function makeHyperlinks($text) {
// Find links and call the makeLink() function on them.
return preg_replace('/((www\.|(http|https|ftp|news|file)+\:\/\/)[_.a-z0-9-]+\.[a-z0-9\/_:#=.+?,##%&~-]*[^.|\'|\# |!|\(|?|,| |>|<|;|\)])/e', "makeLink('$1')", $text);
}
?>
You will want to use a regular expression to match common URL patterns. PHP offers a function called preg_match that allows you to do this.
The regular expression itself could take several forms, but here is something to get you started (also maybe just Google 'URL regex':
'/^(((http|https|ftp)://)?([[a-zA-Z0-9]-.])+(.)([[a-zA-Z0-9]]){2,4}([[a-zA-Z0-9]/+=%&_.~?-]))$/'
So your code should look something this:
$matches = array(); // will hold the results of the regular expression match
$string = "http://www.astringwithaurl.com";
$regexUrl = '/^(((http|https|ftp):\/\/)?([[a-zA-Z0-9]\-\.])+(\.)([[a-zA-Z0-9]]){2,4}([[a-zA-Z0-9]\/+=%&_\.~?\-]*))*$/';
preg_match($regexUrl, $string, $matches);
print_r($matches); // an array of matched patterns
From here, you just want to wrap those URL patterns in an anchor/href tag and you're done.
Just how accurate do you want to be? Given just how varied URLs can be, you're going to have to draw the line somewhere. For instance. www.ca is a perfectly valid hostname and does bring up a site, but it's not something you'd EXPECT to work.
You should investigate regular expressions for this.
You will build a pattern that will match the part of your string that looks like a URL and format it appropriately.
It will come out something like this (lifted this, haven't tested it);
$pattern = "((https?|ftp|gopher|telnet|file|notes|ms-help):((//)|(\\\\))+[\w\d:##%/;$()~_?\+-=\\\.&]*)";
preg_match($pattern, $input_string, $url_matches, PREG_OFFSET_CAPTURE, 3);
$url_matches will contain an array of all of the parts of the input string that matched the url pattern.
You can use $_SERVER['HTTP_HOST'] to get the host information.
<?php
$host = $SERVER['HTTP_HOST'];
?>
Post