Jump to content

Recommended Posts

i'm having trouble in combining the 2 preg_replace into 1.

basically i have a string witch strange chars, first i remove all except alphanumeric chars and the remaining string has 1 or 2 spaces and i replace them with dash.

strtolower(preg_replace('/\s+/', '-', preg_replace("/[^0-9a-zA-Z]/i", ' ',$a['item'])));

Link to comment
https://forums.phpfreaks.com/topic/246177-combining-2-preg_replace/
Share on other sites

I was hoping that you would rethink the logic being used here, but maybe that was too much to ask. 

 

Think about what your regular expressions are doing.

 

1. Replace any single non-alphanumeric character with a space.

2. Replace any occurrence of one or more consecutive whitespace characters with a dash.

 

There is never any chance of an alphanumeric character also being a whitespace character, it's just not possible. Anything non-alphanumeric will become a space, then any group of spaces will become one dash. The above two steps can be replaced with a single one doing the same job:

 

1. Replace one or more consecutive non-alphanumeric characters with a dash.

 

strtolower(preg_replace('/[^0-9a-zA-Z]+/', '-', $a['item']));

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.