regex to replace string with params - php

Please help me to create regex for replace a string like:
/technic/k-700/?type=repair
to a string like
/repair/k-700/
Instead of k-700 can be any another combination (between / ) and instead of repair can be only kit.
I need pattern and replacement, please. It's so hard for me.
My result not working for Wordpress:
$pattern = '/technic/([0-9a-zA-Z-]+)/?type=$matches[1]';
$replacement = '/?/([0-9a-z-]+)/';

You can try something like this:
$test = preg_replace(
'~/\w+/([\w-]+)/\?type=(\w+)~i',
'/$2/$1/',
'/technic/k-700/?type=repair'
);
var_dump($test);
The result will be:
string(14) "/repair/k-700/"

You don't need regex, you can do it simply by using explode():
$str = '/technic/k-700/?type=repair';
$first = explode('/', explode('?', $str)[0]);
$second = explode('=', explode('?', $str)[1]);
$first[1] = $second[1];
echo $new = implode("/",$first);
//output: /repair/k-700/

For the sake of completeness or if you need to access the url parts later.
Here's a solution using parse_url and parse_str
$str = '/technic/k-700/?type=repair';
$url = parse_url($str);
$bits = explode('/',trim($url['path'],'/'));
parse_str($url['query']);
print '/' . $type . '/' . $bits[1] . '/' ;
Which will output
/repair/k-700/

Related

How to remove the first two directories from a file path string?

I have a string "./product_image/Bollywood/1476813695.jpg".
first I remove . from first.
now I want to remove all character between first two / . that means I want
Bollywood/1476813695.jpg
I am trying with this but not work
substr(strstr(ltrim('./product_image/Bollywood/1476813695.jpg', '.'),"/product_image/"), 1);
It always return product_image/Bollywood/1476813695.jpg
Easily done with explode():
$orig = './product_image/Bollywood/1476813695.jpg';
$origArray = explode('/', $orig);
$new = $origArray[2] . '/' . $origArray[3];
result:
Bollywood/1476813695.jpg
If you want something a little different you can use regex with preg_replace()
$pattern = '/\.\/(.*?)\//';
$string = './product_image/Bollywood/1476813695.jpg';
$new = preg_replace($pattern, '', $string);
This returns the same thing and you could, if you wanted, put it all in one line.
$str = "./product_image/Bollywood/1476813695.jpg";
$str_array = explode('/', $str);
$size = count($str_array);
$new_string = $str_array[$size - 2] . '/' . $str_array[$size - 1];
echo $new_string;
please follow the below code
$newstring = "./product_image/Bollywood/1476813695.jpg";
$pos =substr($newstring, strpos($newstring, '/', 2)+1);
var_dump($pos);
and output will be looking
Bollywood/1476813695.jpg
for strpos function detail please go to below link
http://php.net/manual/en/function.strpos.php
for substr position detail please go to below link
http://php.net/manual/en/function.substr.php

PHP Get a part from $string

could you pls help me to parse the string?
the string is:
$str = 'http://test.al/admin/?plugin=pages&act=delete&file=test-page';
It's dynamic and could contain more &-symbols.
I want to get everything but the part starting from "&..."
so the result should be :
http://boot.al/admin/?plugin=pages
need it to Go Back after deleting a file, to clear additional $_GET params.
Thank you in advance!
Use strtok():
<?php
$str = 'http://test.al/admin/?plugin=pages&act=delete&file=test-page';
$result = strtok($str, '&');
var_dump($result); // outputs "http://test.al/admin/?plugin=pages"
$parts = explode('&', $str);
$str = $parts[0];
Convert the string to an array by using & as delimiter.
The first element of the array will hold the part you need
Use parse_url() for this:
$str = 'http://test.al/admin/?plugin=pages&act=delete&file=test-page';
$url_components = parse_url($str);
$get_component = explode("&", $url_components['query']);
$new_str = $url_components['scheme'] . "://" . $url_components['host'] . $url_components['path'] . "?" . $get_component[0];
echo $new_str;
Output:
http://test.al/admin/?plugin=pages

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);
?>

PHP Regex - Getting querystring parameters from rewritten URL

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];

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