PHP Regex - Getting querystring parameters from rewritten URL - php

I need a regex string to extract parameters from different types of url, for example using $_SERVER["REQUEST_URI"]:
string 1: "/news/page/4" or string 2: "/news/weekly/page/4"
I need to extract the string without last /page/[ID], I mean only /news/page or /news/weekly/, etc.
How can I do it with preg_replace?
Thank you.

You can use explode() instead of regular expressions:
$delimiter = '/';
$parts = explode($delimiter, $_SERVER["REQUEST_URI"]);
$whatINeed = $parts[0] . $delimiter . $parts[1];

regexp solution:
echo preg_replace('/^([\w\W]*)\/page\/\d*/','$1','/news/weekly/page/4');
outputs:
/news/weekly
but you should use explode solution:
$parts = explode('/', $_SERVER["REQUEST_URI"]);
$url = $parts[0].'/'.$parts[1];

You should be able to use: [A-Za-z/]+
But it will be slower then just using substr. EDIT: not substr, but explode.

Try:
$foo = explode('/', $_SERVER["REQUEST_URI"]);
$resultant_url = $foo[0].'/'.$foo[1];

Related

How to get last part of a string?

I have this string:
"application/controllers/backend"
I want get:
backend
of course the backend it's dynamic, so could be change, so I'm looking for a solution that allow me to get only the last part of the string. How I can do that?
You can take the advantage of basename() to get the last part
in your case, it will be
basename("application/controllers/backend");
Output:
backend
Some thing like this :
echo end(explode("/", $url));
If this thorws error then do :
$parts = explode("/", $url);
echo end($parts);
$arr = explode ("/", $string);
//$arr[2] is your third element in the string
http://php.net/manual/en/function.explode.php
Just use
basename("application/controllers/backend");
http://php.net/manual/en/function.basename.php
And, if you want to do it with a regex:
$result = (preg_match('%.*[/\\\\](.*?)$%', $url, $regs)) ? $regs[1] : '';
You did ask initially for a solution with regex, so, although the other answers haven't involved regex, here is one approach which does.
You can use preg_match and str_replace for this:
$string = '"application/controllers/backend"';
preg_match('/[^\/]+"/', $string, $matches);
$last_item = str_replace('"','',$matches[0]);
$last_item is now a string containing the word backend.

Parsing the last substring of the url

I want to parse the string after the last "/" .
For example:
http://127.0.0.1/~dtm/index.php/en/parts/engine
Parse the "engine" .
I tried do it with Regexp but as im new to regexp im stuck near the solution.
Also this pattern seems quite easy breakable (/engine/ will break it ) . Need somehow make it a bit more stable.
$pattern = ' \/(.+^[^\/]?) ' ;
/ Match the / char
.+ Match any char one or more times
^[^/\ Exclude \ char
Demo of the current state
You don't need a regex, don't make it complicated just use this:
<?php
$url = "http://127.0.0.1/~dtm/index.php/en/parts/engine";
echo basename($url);
?>
Output:
engine
I recommend you to use performatner functions instead of preg_match to do this
eg basename()
$url = "http://127.0.0.1/~dtm/index.php/en/parts/engine";
echo basename($url);
or explode()
$parts = explode('/',$url);
echo array_pop($parts);
You can also use parse_url(), explode() and array_pop() together to achieve your goal.
<?php
$url = 'http://127.0.0.1/~dtm/index.php/en/parts/engine';
$parsed = parse_url($url);
$path = $parsed['path'];
echo array_pop(explode('/', $path));
?>
PhpFiddle Demo
Is this something?
$url = "http://127.0.0.1/~dtm/index.php/en/parts/engine";
$ending = end(explode('/', $url));
Output:
engine

Replace a specified portion of a string

How can I use str_replace method for replacing a specified portion(between two substrings).
For example,
string1="www.example.com?test=abc&var=55";
string2="www.example.com?test=xyz&var=55";
I want to replace the string between '?------&' in the url with ?res=pqrs&. Are there any other methods available?
You could use preg_replace to do that, but is that really what you are trying to do here?
$str = preg_replace('/\?.*?&/', '?', $input);
If the question is really "I want to remove the test parameter from the query string" then a more robust alternative would be to use some string manipulation, parse_url or parse_str and http_build_query instead:
list($path, $query) = explode('?', $input, 2);
parse_str($query, $parameters);
unset($parameters['test']);
$str = $path.'?'.http_build_query($parameters);
Since you're working with URL's, you can decompose the URL first, remove what you need and put it back together like so:
$string1="www.example.com?test=abc&var=55";
// fetch the part after ?
$qs = parse_url($string1, PHP_URL_QUERY);
// turn it into an associative array
parse_str($qs, $a);
unset($a['test']); // remove test=abc
$a['res'] = 'pqrs'; // add res=pqrs
// put it back together
echo substr($string1, 0, -strlen($qs)) . http_build_query($a);
There's probably a few gotchas here and there; you may want to cater for edge cases, etc. but this works on the given inputs.
Dirty version:
$start = strpos($string1, '?');
$end = strpos($string1, '&');
echo substr($string1, 0, $start+1) . '--replace--' . substr($string1, $end);
Better:
preg_replace('/\?[^&]+&/', '?--replace--&', $string1);
Depending on whether you want to keep the ? and &, the regex can be mofidied, but it would be quicker to repeat them in the replaced string.
Think of regex
<?php
$string = 'www.example.com?test=abc&var=55';
$pattern = '/(.*)\?.*&(.*)/i';
$replacement = '$1$2';
$replaced = preg_replace($pattern, $replacement, $string);
?>

Use preg_match to grab value from URL

I have a url something like:
www.yourname.mysite.com/templates/diversity/index.php
I need to grab that string, "diversity", and match it against a db value. I've never used anything like preg_match in php, how can I grab that string?
Instead of a regular expression, you can use parse_url() for that:
$url = 'www.yourname.mysite.com/templates/diversity/index.php';
$parts = parse_url($url);
$paths = explode('/', $parts['path']);
// "diversity" is in $paths[1]
For completeness' sake, here's the regular expression:
preg_match('=^[^/]+/[^/]+/([^/]+)/=', $url, $matches);
// "diversity" is in $matches[1]
$ex = explode("/",$_SERVER["PHP_SELF"]);
echo $ex[2];
You can just explode that string and get the third value of the resulting array:
$parts = explode("/", "www.yourname.mysite.com/templates/diversity/index.php");
echo $parts[2]; // diversity

sub string replacment in PHP

I have a string like:
$string = "/physics/mechanics/vectors/P-M-C (1).doc";
I want to get like this:
"/physics/mechanics/vectors/1-P-M-C (1).doc";
Please note that "1-" is added just before P in the original string.
Is it possible in PHP?
How the function in PHP should be used?
#fawad:Here's a sample to get you started --
$oldstring = "/physics/mechanics/vectors/P-M-C (1).doc";
$parts = explode("/", $oldstring);
$file = $parts[count($parts) - 1];
$newstring = str_replace($file, "1-" . $file, $oldstring);
Take a look at explode() and join() for this. :)

Categories