PHP fix ()

Suppose I have $url="../folder/file" and I want to find and delete the ../ part.

I am using trim() ...

 $url = trim($url,"../"); 

... but this gives me a warning:

Warning: trim () [function.trim]: Invalid ".." range, not a single character to the left of ".." in the line above

What have I done wrong?

+4
source share
5 answers

what you did wrong, did not read the manual:

With .. you can specify a range of characters.

 <?php $url="../folder/file"; $url = trim($url,"\.\./"); echo $url; ?> 
+4
source

you can use ltrim

 echo ltrim("../folder/file", "./"); 

or

 echo trim("../folder/file", "./"); 
+2
source

There is a special syntax for the trim function from php.net/trim , which allows you to specify the range that, according to the translator, is because of ".."

 // trim the ASCII control characters at the beginning and end of $binary // (from 0 to 31 inclusive) $clean = trim($binary, "\x00..\x1F"); var_dump($clean); 

The second argument to trim should be a string of characters that would be stripped out, so you won't need to put '.' twice.

0
source

The second argument to the trim function specifies the list of characters to be deleted, rather than a multi-character string. The function interprets ".." as an operator that defines a range of characters (for example, a..z or 1..5). You can cut "../" in several ways, but one is simple:

 $parts = explode('/', $url); array_shift($parts); $url = implode('/', $parts); 
0
source

I found this feature in the bottom comments of the cropping page on php.net, which seems to do what you want

 function trimString($input, $string){ $input = trim($input); $startPattern = "/^($string)+/i"; $endPattern = "/($string)+$/i"; return trim(preg_replace($endPattern, '', preg_replace($startPattern,'',$input))); } 
0
source

Source: https://habr.com/ru/post/1397717/


All Articles