Reputation: 69
I want to remove a known string (four of them actually) whichever one is printed, eg. one, two, three or four.
or the same effect would be removing the string after the last slash
I'm exploding the url to get strings from them but i only want to keep the string until the last dash. eg of url http://www.website.com/page/nameIwantTokeep-RemoveThis/product/ i want to remove RemoveThis on the actual page
$path = $_SERVER['REQUEST_URI'];
$build = strpos($path, 'back')||
strpos($path, 'front');
if ($build > 0) {
$array = explode('/',$path);
$slice = (array_slice($array, 2, 1));
foreach($slice as $key => $location);
Upvotes: 2
Views: 2572
Reputation: 13640
You can use the following to match:
(-(?!.*-)[^\/]*)
and replace with ''
(empty string)
See DEMO
Upvotes: 0
Reputation: 36
I know your question was about regex but i don't really see a need for it. You should consider using strrpos to find the index of the last dash in your string and take the substring (substr) you need.
$input = "whatever-removethis";
$index = strrpos($input, "-");
if(index === false) //in case no dash was found
{
$output = $input;
}
else
{
$output = substr($input, 0, $index);
}
http://php.net/manual/en/function.strrpos.php
http://php.net/manual/en/function.substr.php
Upvotes: 2
Reputation: 785276
Using regex:
Search using this regex:
-[^/-]+(?![^-]*-)
Replace by empty string.
Code:
$re = "~-[^/-]+(?![^-]*-)~";
$str = "http://www.website.com/page/name-IwantTokeep-RemoveThis/product/";
$result = preg_replace($re, "", $str, 1);
Upvotes: 4