Jump to content

combining 2 preg_replace


dsp77

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']));

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.