如何从php中的url中获取单词?

url string

http://localhost/magento_prac/index.php/electronics/computers.html
http://localhost/magento_prac/index.php/electronics/cell-phones.html

I want to fetch 'computers' from url. ex 'computers', 'cell-phones'

Try something like

$category = preg_replace('/^.*\/(.*)\.html$/', '$1', $url);

The regular expression matches everything (.*) from the start (^) of the string up until the last / (\/). Then, it matches everything (.*) again except for the .html at the end and expects the string to end after that ($).

The brackets around the second .* allow you to reference that part of the match in the substitution as $1.

You can convert URL into attay and fetch last element with array_pop():

$urlArray = explode('/', $url);
$word = substr(array_pop($urlArray),0,-5);

try this code:

//get the url
$url = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

//seperate the segments using explode()
$segments = explode('/', $url);

//and get the last segment
$last = explode('.', end($segments));

//use the last segment
echo $last[0];

For convenience, here's another option:

$url = 'http://localhost/magento_prac/index.php/electronics/computers.html';
$category = pathinfo($url)['filename']; // "computers"

Above example assumes the application is running at least on PHP 5.4 to use array de-referencing.

pathinfo - Returns information about a file path.

'dirname' => string 'http://localhost/magento_prac/index.php/electronics'
'basename' => string 'computers.html'
'extension' => string 'html'
'filename' => string 'computers'