how to write a regular expression

Asked 1 years ago, Updated 1 years ago, 41 views


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.

php

2022-09-30 21:21

3 Answers

A function called basename is provided to extract the last name from the path.

$php-r'echo basename("/category/tops/knit-sweater/");'


2022-09-30 21:21

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];


2022-09-30 21:21

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 $.


2022-09-30 21:21

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.