php removes the subcharacter at the end of the string the beginning character and the of implementation code at both ends

  • 2020-06-22 23:57:52
  • OfStack

Today I had the following problem with deleting specific characters at both ends of a string. Let's look at the example first
< SPAN style="FONT-SIZE: 18px" > < /SPAN >
$str = 'akmumu/writedb.json';
What I want to do is delete akmumu at the beginning and.json at the end, so that only the useful characters /writedb remain
First I used ltrim to delete akmumu, then rtrim to delete.json
It turns out that I understand trim incorrectly. The parameters of trim are as follows
rtrim(string,charlist)
His parameter is charlist, which is not 1 and he looks it up in that order, let's say I give 1
$str = 'akmumu/writedbsojn.json';
The result is /write again, I want /writedbsojn did not appear, which means as long as any character in charlist matches, 1 will go on like this...
So I use something else
str_replace, substr_replace can
To be safe, code has been added to prevent further interception of errors

if(strpos($str,'akmumu/') !== FALSE
 $str = substr($str,7);
 if(strpos($str,'.json') !== FALSE)
 {
  if(substr($str,-5,5) == '.json')
  {
   $str = substr_replace($str,'',-5);
  }
 } 
}

That will do

Related articles: