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
Related
I want to ouput only MYID from URL. What I did so far:
$url = "https://whatever.expamle.com/display/MYID?out=1234567890?Browser=0?OS=1";
echo substr($url, 0, strpos($url, "?out="));
output: https://whatever.expamle.com/display/MYID
$url = preg_replace('#^https?://whatever.expamle.com/display/#', '', $url);
echo $url;
ouput: MYID?out=1234567890?Browser=0?OS=1
How can I combine this? Thanks.
For a more general solution, we can use regex with preg_match_all:
$url = "https://whatever.expamle.com/display/MYID?out=1234567890?Browser=0?OS=1";
preg_match_all("/\/([^\/]+?)\?/", $url, $matches);
print_r($matches[1][0]); // MYID
When the string is always a Uniform Resource Locator (URL), like you present it in your question,
given the following string:
$url = "https://whatever.expamle.com/display/MYID?out=1234567890?Browser=0?OS=1";
you can benefit from parsing it first:
$parts = parse_url($url);
and then making use of the fact that MYID is the last path component:
$str = preg_replace(
'~^.*/(?=[^/]*$)~' /* everything but the last path component */,
'',
$parts['path']
);
echo $str, "\n"; # MYID
and then depending on your needs, you can combine with any of the other parts, for example just the last path component with the query string:
echo "$str?$parts[query]", "\n"; # MYID?out=1234567890?Browser=0?OS=1
Point in case is: If the string already represents structured data, use a dedicated parser to divide it (cut it in smaller pieces). It is then easier to come to the results you're looking for.
If you're on Linux/Unix, it is even more easy and works without a regular expression as the basename() function returns the paths' last component then (does not work on Windows):
echo basename(parse_url($url, PHP_URL_PATH)),
'?',
parse_url($url, PHP_URL_QUERY),
"\n"
;
https://php.net/parse_url
https://php.net/preg_replace
https://www.php.net/manual/en/regexp.reference.assertions.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/
I need to extract only parts of a URL with PHP but I am struggling to the set point where the extraction should stop. I used a regex to extract the entire URL from a longer string like this:
$regex = '/\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|$!:,.;]*[A-Z0-9+&##\/%=~_|$]/i';
preg_match_all($regex, $href, $matches);
The result is the following string:
http://www.cambridgeenglish.org/test-your-english/&sa=U&ei=a4rbU8agB-zY0QWS_IGYDw&ved=0CFEQFjAL&usg=AFQjCNGU4FMUPB2ZuVM45OoqQ39rJbfveg
Now I want to extract only this bit http://www.cambridgeenglish.org/test-your-english/. I basically need to get rid off everything starting at & onwards.
Anyone an idea how to achieve this? Do I need to run another regex or can I add it to the initial one?
I would suggest you abandon regex and let PHP's own parse_url function do this for you:
http://php.net/manual/en/function.parse-url.php
$parsed = parse_url($url);
$my_url = $parsed['scheme'] . '://' . $parsed['hostname'] . $parsed['path'];
to get the substring of the path up to the &, try:
$parsed = parse_url($url);
$my_url = $parsed['scheme'] . '://' . $parsed['hostname'] . substr($parsed['path'], 0, strpos($parsed['path'],'&'));
The below regex would get ridoff everything after the string &. Your php code would be,
<?php
echo preg_replace('~&.*$~', '', 'http://www.cambridgeenglish.org/test-your-english/&sa=U&ei=a4rbU8agB-zY0QWS_IGYDw&ved=0CFEQFjAL&usg=AFQjCNGU4FMUPB2ZuVM45OoqQ39rJbfveg');
?> //=> http://www.cambridgeenglish.org/test-your-english/
Explanation:
& Matches the string &.
.* Matches any character zero or more times.
$ End of the line.
Hi i want to know how can i get substring from string after last slash?
In short i want to get the file name from path.
for example i got string like this:
test-e2e4/test-e2e4/test-e2e4/6.png
and i want to get 6.png how can i do that ?
I got dir only and the file name can be all format, it can be also something else then file
Or test-e2e4/test-e2e4/test-e2e4/aaaaa and want to get aaaaa
Regex maybe? Or maybe you know some nice functions which will do it for me ?
In addition to other replies, there's actually a function in PHP to do this: basename. Example:
$string = 'test-e2e4/test-e2e4/test-e2e4/6.png';
$base = basename($string); // $base == '6.png';
$string = 'test-e2e4/test-e2e4/test-e2e4/aaaaa';
$base = basename($string); // $base == 'aaaaa'
$string = '6.png';
$base = basename($string); // $base == '6.png'
Full details here: http://php.net/basename
Do like this..
$yourstring = 'test-e2e4/test-e2e4/test-e2e4/6.png';
$val = array_pop(explode('/',$yourstring)); // 6.png
You can try explode and array_pop functions to work this out:
$str = 'test-e2e4/test-e2e4/test-e2e4/aaaaa.png';
$str = explode('/', $str);
$filename = array_pop($str);
echo $filename; //Output will be aaaaa.png
...Or you can use the following regex:
[^\/]*$
You don't need to use regex for this, you can use substr() to get a portion of the string, and strrpos() to specify which portion:
$full_path = "test-e2e4/test-e2e4/test-e2e4/6.png"
$file = substr( $full_path, strrpos( $full_path, "/" ) + 1 );
substr() returns a portion of the string, strrpos() tells it to start from the position of the last slash in the string, and the +1 excludes the slash from the return value.
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];