Replace more than one forward slash - php

I'd like to replace more than one forward slash with one forward slash.
Examples:
this/is//an//example -> this/is/an/example
///another//example//// -> /another/example/
example.com///another//example//// -> example.com/another/example/
Thanks!
EDIT: This will be used to fix URLs that have more than one forward slash.

try
preg_replace('#/+#','/',$str);
or
preg_replace('#/{2}#','/',$str);
Tips: use str_replace for such a simple replacement AS it
replace all occurrences of the search string with the replacement string
str_replace('/','/',$str);
Reference

You might want to use regex:
$modifiedString = preg_replace('|/{2,}|','/',$strToModify);
I use the {2,} instead of + to avoid replacing single '/'.

Use a regex to replace one or more /-es with /:
$string = preg_replace('#/+#', '/', $string);
I see you want to create a valid url... you might want to check out realpath, or maybe even better the snippet in the first comment:
$path = '../gallery/index/../../advent11/app/';
$pattern = '/\w+\/\.\.\//';
while(preg_match($pattern, $path)) {
$path = preg_replace($pattern, '', $path);
}
// $path == '../advent11/app/'
As you can see this also solves ../-es :)

Related

PHP Regex to get second occurance from the path

I have a path "../uploads/e2c_name_icon/" and I need to extract e2c_name_icon from the path.
What I tried is using str_replace function
$msg = str_replace("../uploads/","","../uploads/e2c_name_icon/");
This result in an output "e2c_name_icon/"
$msg=str_replace("/","","e2c_name_icon/")
There is a better way to do this. I am searching alternative method to use regex expression.
Try this. Outputs: e2c_name_icon
<?php
$path = "../uploads/e2c_name_icon/";
// Outputs: 'e2c_name_icon'
echo explode('/', $path)[2];
However, this is technically the third component of the path, the ../ being the first. If you always need to get the third index, then this should work. Otherwise, you'll need to resolve the relative path first.
Use basename function provided by PHP.
$var = "../uploads/e2c_name_icon/";
echo basename( $var ); // prints e2c_name_icon
If you are strictly want to get the last part of the url after '../uploads'
Then you could use this :
$url = '../uploads/e2c_name_icon/';
$regex = '/\.\.\/uploads\/(\w+)/';
preg_match($regex, $url, $m)
print_r ($m); // $m[1] would output your url if possible
You can trim after the str_replace.
echo $msg = trim(str_replace("../uploads/","","../uploads/e2c_name_icon/"), "/");
I don't think you need to use regex for this. Simple string functions are usually faster
You could also use strrpos to find the second last /, then trim off both /.
$path = "../uploads/e2c_name_icon/";
echo $msg = trim(substr($path, strrpos($path, "/",-2)),"/");
I added -2 in strrpos to skip the last /. That means it returns the positon of the / after uploads.
So substr will return /e2c_name_icon/ and trim will remove both /.
You'd be much better off using the native PHP path functions vs trying to parse it yourself.
For example:
$path = "../uploads/e2c_name_icon/";
$msg = basename(dirname(realpath($path))); // e2c_name_icon

How to replace last backward slash with forward slash PHP

I want to replace my last \ with / on this URL string
C:\wamp\www\chm-lib\sekhelp_out\HTML\AS_BUILD.htm
I have tried this link, but no changes, I am missing something, please correct me where I am wrong.
Here is a solution using PHP's string functions instead of regex.
Do this:
$url = 'C:\wamp\www\chm-lib\sekhelp_out\HTML\AS_BUILD.htm';
$pos = strrpos($url, '\\');
$url = substr_replace($url, '/', $pos, 1);
echo $url;
To get this:
C:\wamp\www\chm-lib\sekhelp_out\HTML/AS_BUILD.htm
Explanation:
Get the position of the last \ in the input string using strrpos()
Replace that with / using substr_replace()
Note
It is important to pass '\\' instead of '\' to strrpos() as the first \ escapes the second.
Also note that you can shorten the code above to a single line if you prefer, but I thought it would be easier to understand as is. Anyway, here is the code as a one-liner function:
function reverseLastBackslash($url) {
return substr_replace($url, '/', strrpos($url, '\\'), 1);
}
You can try exploding the string as an array and imploding after popping off the last part, and connecting it back with a forward slash.
$array = explode('\','C:\wamp\www\chm-lib\sekhelp_out\HTML\AS_BUILD.htm');
$last = array_pop($array);
$corrected = implode('\',$array) . '/' . $last;
The backslash escaping is tricky:
preg_replace('/\\\\([^\\\\]*)$/', '/$1', "C:\\wamp\\www\\chm-lib\\sekhelp_out\\HTML\\AS_BUILD.htm")
You have to escape once for the literal string and once for the regular expression so a single \ needs to be \\\\ (1 x 2 x 2)
Simply use this
str_replace('\\','/','C:\wamp\www\chm-lib\sekhelp_out\HTML\AS_BUILD.htm');

Effective way to remove everything after last ? from string

I am trying to strip everything that follows and includes the last ? of a given url. I am currently working with preg_replace but no luck in accomplishing the goal. This is the regex #\/[^?]*$# I am using to single out the last ?. Also is there a faster way by using substr?
Example link:
preg_replace('#\/[^?]*$#', '', $post="www.exapmle.com?26sf213132aasdf1312sdf31")
Desired Output
www.example.com
Here's how to do it with substr and strrpos:
$post = "www.exapmle.com?26sf213132aasdf1312sdf31";
$pos = strrpos($post, '?');
$result = substr($post, 0, $pos);
Add a \? at start of regex instead of \/
\?[^?]*$
\? matches a ?
[^?]*$ matches anything other than a ? until the end of string anchored by $
Example http://regex101.com/r/sW6jE7/3
$post="www.exapmle.com?26sf213132aasdf1312sdf31";
$res=preg_replace('/\?[^?]*$/', '', $post);
echo $res;
will give an output
www.example.com
EDIT
If you want to remove the entire query string from url then a slight modifiation of regex would do the work
\?.*$
which will remove anything followed by a question mark
Simply match everything from the start upto the ? symbol.
preg_match('/^[^?\n]*/', $post="www.exapmle.com?26sf213132aasdf1312sdf31", $match);
echo $match[0];
Output:
www.exapmle.com
Try this its working fine :
$host_url = "www.exapmle.com?26sf213132aasdf1312sdf31";
$part_url = strrpos($host_url, '?');
$result = substr($host_url, 0, $part_url);
echo $result;
Although OP tags regex, Surprisingly nobody suggests explode(), which is much easier.
$post = "www.exapmle.com?26sf213132aasdf1312sdf31";
$tokens = explode('?', $post);
echo $tokens[0]; // www.exapmle.com

String replace with wildcard

I have a string http://localhost:9000/category that I want to replace with category.html, i.e. strip everything before /category and add .html.
But can't find a way to do this with str_replace.
You want to use parse_url in this case:
$parts = parse_url($url);
$file = $parts['path'].'.html';
Or something along that line. Experiment a bit with it.
Ismael Miguel suggested this shorter version, and I like it:
$file = parse_url($url,PHP_URL_PATH).'.html';
Much better than a ^*!$(\*)+ regular expression.
.*\/(\S+)
Try this.Replace by $1.html.see demo .
http://regex101.com/r/nA6hN9/43
Use preg_replace instead of str_replace
Regex:
.*\/(.+)
Replacement string:
$1.html
DEMO
$input = "http://localhost:9000/category";
echo preg_replace("~.*/(.+)~", '$1.html', $input)
Output:
category.html
A solution without regex:
<?php
$url = 'http://localhost:9000/category';
echo #end(explode('/',$url)).'.html';
?>
This splits the string and gets the last part, and appends .html.
Note that this won't work if the input ends with / (e.g.: $url = 'http://localhost:9000/category/';)
Also note that this relies on non-standard behavior and can be easily changed, this was just made as a one-liner. You can make $parts=explode([...]); echo end($parts).'.html'; instead.
If the input ends with / occasionally, we can do like this, to avoid problems:
<?php
$url = 'http://localhost:9000/category/';
echo #end(explode('/',rtrim($url,'/'))).'.html';
?>

Removing content from start and end of string (PHP)

I'm trying to get a users ID from a string such as:
http://www.abcxyz.com/123456789/
To appear as 123456789 essentially stripping the info up to the first / and also removing the end /. I did have a look around on the net but there seems to be so many solutions but nothing answering both start and end.
Thanks :)
Update 1
The link can take two forms: mod_rewrite as above and also "http://www.abcxyz.com/profile?user_id=123456789"
I would use parse_url() to cleanly extract the path component from the URL:
$path = parse_URL("http://www.example.com/123456789/", PHP_URL_PATH);
and then split the path into its elements using explode():
$path = trim($path, "/"); // Remove starting and trailing slashes
$path_exploded = explode("/", $path);
and then output the first component of the path:
echo $path_exploded[0]; // Will output 123456789
this method will work in edge cases like
http://www.example.com/123456789?test
http://www.example.com//123456789
www.example.com/123456789/abcdef
and even
/123456789/abcdef
$string = 'http://www.abcxyz.com/123456789/';
$parts = array_filter(explode('/', $string));
$id = array_pop($parts);
If the ID always is the last member of the URL
$url="http://www.abcxyz.com/123456789/";
$id=preg_replace(",.*/([0-9]+)/$,","\\1",$url);
echo $id;
If there is no other numbers in the URL, you can also do
echo filter_var('http://www.abcxyz.com/123456789/', FILTER_SANITIZE_NUMBER_INT);
to strip out everything that is not a digit.
That might be somewhat quicker than using the parse_url+parse_str combination.
If your domain does not contain any numbers, you can handle both situations (with or without user_id) using:
<?php
$string1 = 'http://www.abcxyz.com/123456789/';
$string2 = 'http://www.abcxyz.com/profile?user_id=123456789';
preg_match('/[0-9]+/',$string1,$matches);
print_r($matches[0]);
preg_match('/[0-9]+/',$string2,$matches);
print_r($matches[0]);
?>

Categories