PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, November 20, 2022

[FIXED] How to remove whitespace + hiphen + whitespace to only hiphen in url slug with preg_replace

 November 20, 2022     preg-replace, removing-whitespace, slug     No comments   

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

Php demo



Answered By - The fourth bird
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing