Issue
I am using this function. Everything works fine but When i enter item title like : "Example - A digital product" it shows me in url slug example---a-digital-product..Here after word example there are 3 hiphen continuous. Please help to resolve it.
public function item_slug($string){
$slug=preg_replace(array('/[^A-Za-z0-9 -]+/','/[ -]+/'), array('',''),$string);
return $slug;
}
Solution
You could use a hyphen in the second replacement to replace 1 or more occurrences of a space or hyphen you match with [ -]+
with a single hyphen.
Example code:
function item_slug($string){
return preg_replace(array('/[^A-Za-z0-9 -]+/','/[ -]+/'), array('','-'),$string);
}
$strings = [
"example---a-digital-product..",
"Example - A digital product"
];
foreach ($strings as $str) {
echo item_slug($str) . PHP_EOL;
}
Output
example-a-digital-product
Example-A-digital-product
Answered By - The fourth bird Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.