My webpage has a variable, $currentPage. This is a string of the php token name of the page I'm currently on.
Example: All categories under the user section have names such as:
uAdminNew, uAdminEdit, ect..
I would like for a way to parse out the uAdmin and just determine what is the last word (New and Edit) and call upon functions from there.
I have my navigation system working through these names, therefore I can't change the names or I would to make it easier to parse. Such as adding delimiters.
Is this something only Regex can solve or is there a simpler solution I'm missing? If this is Regex could you explain or provide a link as to how I would go about using it to test against a specific list of strings? I'm very new to it.
For example, so:
$str = 'uAdminEdit';
$ar = preg_match('/([A-Z][^A-Z]+$)/', $str, $m);
echo $m[1]; // Edit
Does the pagename always start with uAdmin? If so, you could split the string by "uAdmin" with explode():
$page = 'uAdminEdit';
echo explode('uAdmin', $page)[1]; //Output: Edit
Or simply remove "uAdmin" with str_replace():
$page = 'uAdminEdit';
echo str_replace('uAdmin', '', $page); //Output: Edit
If you just want the section after uAdmin, use the regex capture groups
preg_match('/uAdmin(.*)/', $sub, $matches);
echo $matches[1]
Related
I have two regex(s) on the way of my input, these:
// replace a URL with a link which is like this pattern: [LinkName](LinkAddress)
$str= preg_replace("/\[([^][]*)]\(([^()]*)\)/", "<a href='$2' target='_blank'>$1</a>", $str);
// replace a regular URL with a link
$str = preg_replace("/(\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|])/i","untitled", $str);
Now there is a problem (somehow a collision). For regular URLs everything is fine. But for a pattern-based URLs, there is a problem: The first regex create a link of that and second regex again create a link of its href-attribute value.
How can I fix it?
Edit: According to the comments, how can I create a single regex instead of those two regex? (using preg_replace_callback). Honestly I tried it but it doesn't work for none kind of URLs ..
Is combining them possible? Because the output of those isn't identical. The first one has a LinkName and the second one has a constant string untitled as its LinkName.
$str = preg_replace_callback('/\[([^][]*)]\(([^()]*)\)|(\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|])/i',
function($matches) {
if(isset($matches[3])) {
// replace a regular URL with a link
return "<a href='".$matches[3]."' target='_blank'>untitled</a>";
} else {
// replace a URL with a link which is like this pattern: [LinkName](LinkAddress)
return "<a href=".$matches[2]." target='_blank'>".$matches[1]."</a>";
}
}, $str);
echo $str;
One way would be to do it like this. You merge your two expressions together with the alternative character |. Then in your callback function you just check if your third capture group is set (isset($matches[3])) and if yes, then your second regular expression matched the string and you replace a normal link, otherwise you replace with link/linktext.
I hope you understand everything and I could help you.
If I have a string of text from Twitter, such as:
$string = "This is a link http://t.co/252351ga to follow.";
How can I unwrap the link, and re-insert into the original string as follows:
$new_string = "This is a link http://www.example.org/article/23534 to follow.";
It's a two-part problem. First you need a regex to find and extract the URLs. It's best to use preg_replace_callback there for simplicity. (You'll find any number of nicer regexs, if you use the search.)
= preg_replace_callback('#http://\S+#', "replace_url_callback", $html)
Second, you either use a shortened URL expansion service/API, or request the URLs yourself and check for redirects or the according meta tag in the response. (For example: http://jamiethompson.co.uk/web/2010/05/18/expanding-short-urls-with-php-expand_url-php-function/ - Forgot the service name I read about lately.. Nevermind, it's simply called "LongURL.org". Not affiliated.)
You probably want to use something like preg_replace and use a pattern to match URLs and replace the match with your own URL.
EDIT:
You can find a good URL regexp here:
http://flanders.co.nz/2009/11/08/a-good-url-regular-expression-repost/
Then use it as follows:
$string = "This is a link http://t.co/252351ga to follow.";
$pattern = ''; //the pattern from the link
$replacement = 'http://www.example.org/article/23534';
echo preg_replace($pattern, $replacement, $string);
I have a feeling that I might be missing something very basic. Anyways heres the scenario:
I'm using preg_replace to convert ===inputA===inputB=== to inputA
This is what I'm using
$new = preg_replace('/===(.*?)===(.*?)===/', '$1', $old);
Its working fine alright, but I also need to further restrict inputB so its like this
preg_replace('/[^\w]/', '', every Link or inputB);
So basically, in the first code, where you see $2 over there I need to perform operations on that $2 so that it only contains \w as you can see in the second code. So the final result should be like this:
Convert ===The link===link's page=== to The link
I have no idea how to do this, what should I do?
Although there already is an accepted answer: this is what the /e modifier or preg_replace_callback() are for:
echo preg_replace(
'/===(.*?)===(.*?)===/e',
'"$1"',
'===inputA===in^^putB===');
//Output: inputA
Or:
function _my_url_func($vars){
return ''.$vars[2].'';
}
echo preg_replace_callback(
'/===(.*?)===(.*?)===/',
'_my_url_func',
'===inputA===inputB===');
//Output: inputB
Try preg_match on the first one to get the 2 matches into variables, and then use preg_replace() on the one you want further checks on?
Why don't you do extract the matches from the first regex (preg_match) and treat thoses results and then put them back in a HTML form ?
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().
How do I extract foo from the following URL and store it in a varialbe, using regex in php?
http://example.com/pages/foo/inside.php
I googled quite a bit for an answer but most regex examples were too complex for me to understand.
preg_match('~pages/(.+?)/~', "http://example.com/pages/foo/inside.php", $matches);
echo $matches[1];
Well, there could be multiple solutions, based on what rule you want the foo to be extracted. As you didn't specify it yet, I'll just guess that you want to get the folder name of the current file (if that's wrong, please expand your question).
<?php
$str = 'http://example.com/pages/foo/inside.php';
preg_match( '#/([^/]+)/[^/]+$#', $str, $match );
print_r( $match );
?>
If the first part is invariant:
$s = 'http://example.com/pages/foo/inside.php';
preg_match('#^http://example.com/pages/([^/]+).*$#', $s, $matches);
$foo = $matches[1];
The main part is ([^/]+) which matches everything which is not a slash (/). That is, we're matching until finding the next slash or end of the string (if the "foo" part can be the last).
$str = 'http://example.com/pages/foo/inside.php';
$s=parse_url($str);
$whatiwant=explode("/",$s['path']);
print $whatiwant[2];