with a string similar to the following:
/category/tops/knit-sweater/
I'd like to get the letter from the last / to the previous / (knit-sweater in this case).
How do I write a regular expression to achieve this?
Please let me know if you know more.
Thank you for your cooperation.
A function called basename
is provided to extract the last name from the path.
$php-r'echo basename("/category/tops/knit-sweater/");'
Personally, I think it's enough to use regular expressions.
Can't I do the following?
$str='/category/tops/knit-sweater/';
$expArray=explode('/',$str);
$index=count($expArray)-2;// Last index
$hosiiStr=$expArray[$index];
There are few samples, so I may have misread your intentions, but I think I can accomplish my purpose with this.
$str='/category/tops/knit-sweater/';
$pattern='#/([^/]*)/$#';
$matches=[];
if(preg_match($pattern,$str,$matches){
print($matches[1]);//->knit-sweater
}
You may still need to fine-tune the last /
, but if you want to take out the last one, you can often use $
.
© 2024 OneMinuteCode. All rights reserved.