preg_replace with dash

Hi,

Just a quick question. I'm wondering if this code:
     function create_slug($string){  
    $slug=preg_replace('/[^A-Za-z0-9-]+/', '-', $string);  
    return $slug;  
  }  

Open in new window


will replace all instances of any character that is a letter or number with the dash. It's supposed to create user friendly post slugs from title string to use within URLs.

Thanks,
Victor
Victor KimuraSEO, Web DeveloperAsked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
Beverley PortlockConnect With a Mentor Commented:
The pattern you posted '/[^A-Za-z0-9-]+/' will replace all characters that are NOT 0-9, A-Z, a-z or a dash

0
 
Vimal DMSenior Software EngineerCommented:
Hai,

Just a slight modification there in your function

  function create_slug($string){  
    $slug=preg_replace('/[^A-Za-z]+/', '-', $string);
      
    return $slug;  
  }  
0
 
Victor KimuraSEO, Web DeveloperAuthor Commented:
Hi bportlock,

Where is the NOT sign?

Thanks,
Victor
0
Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
käµfm³d 👽Connect With a Mentor Commented:
[^ ... ]

Open in new window


Means any character not in this character set. Remove the chevron to make it any character in this set.
0
 
käµfm³d 👽Connect With a Mentor Commented:
P.S.

The chevron only makes it a "not" when it is listed as the first character in the character set. Listed anywhere else, it is a literal character.

Examples:

[^abc]  - Any character NOT a, b, or c
[abc]   - a, b, or c
[abc^]  - a, b, c, or chevron
[^abc^] - Any character NOT a, b, c, or chevron
[^^]    - Any character NOT a chevron

Open in new window

0
 
Beverley PortlockConnect With a Mentor Commented:
"....Means any character not in this character set. Remove the chevron to make it any character in this set....."

Why didn't they use ! to mean NOT like many programming languages..... oh well

@vkimura2007 - I can understand your confusion look at this

 /^[^a-z]+[a-z]*$/

That means "any string starting (^) with characters that are NOT a-z ([^a-z]) ..... " etc. It's unfortunate that regex syntax looks like the leftovers from the Scrabble box....
0
 
käµfm³d 👽Commented:
>>  ...regex syntax looks like the leftovers from the Scrabble box...

lol   = )
0
 
Victor KimuraSEO, Web DeveloperAuthor Commented:
Thanks, fellas. I totally agree. They should have simplified the regex patterns and be consistent with the other programming languages. =)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.