Reputation: 7737
I have a string http://localhost:9000/category
that I want to replace with category.html
, i.e. strip everything before /category
and add .html
.
But can't find a way to do this with str_replace.
Upvotes: 0
Views: 755
Reputation: 16716
You want to use parse_url
in this case:
$parts = parse_url($url);
$file = $parts['path'].'.html';
Or something along that line. Experiment a bit with it.
Ismael Miguel suggested this shorter version, and I like it:
$file = parse_url($url,PHP_URL_PATH).'.html';
Upvotes: 3
Reputation: 4251
A solution without regex:
<?php
$url = 'http://localhost:9000/category';
echo @end(explode('/',$url)).'.html';
?>
This splits the string and gets the last part, and appends .html
.
Note that this won't work if the input ends with /
(e.g.: $url = 'http://localhost:9000/category/';
)
Also note that this relies on non-standard behavior and can be easily changed, this was just made as a one-liner. You can make $parts=explode([...]); echo end($parts).'.html';
instead.
If the input ends with /
occasionally, we can do like this, to avoid problems:
<?php
$url = 'http://localhost:9000/category/';
echo @end(explode('/',rtrim($url,'/'))).'.html';
?>
Upvotes: 0
Reputation: 174736
Use preg_replace
instead of str_replace
Regex:
.*\/(.+)
Replacement string:
$1.html
$input = "http://localhost:9000/category";
echo preg_replace("~.*/(.+)~", '$1.html', $input)
Output:
category.html
Upvotes: 1
Reputation: 67968
.*\/(\S+)
Try this.Replace by $1.html
.see demo .
http://regex101.com/r/nA6hN9/43
Upvotes: 1