dsp77 Posted September 1, 2011 Share Posted September 1, 2011 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 More sharing options...
salathe Posted September 1, 2011 Share Posted September 1, 2011 Why do you want to combine two completely unrelated regular expressions, with two completely unrelated replacement values, into one? Link to comment https://forums.phpfreaks.com/topic/246177-combining-2-preg_replace/#findComment-1264267 Share on other sites More sharing options...
dsp77 Posted September 1, 2011 Author Share Posted September 1, 2011 from what i understand is ok like this? when i code i'm trying to make the simplest and fastest code that's why asked if can be one preg_replace doing all the job. Link to comment https://forums.phpfreaks.com/topic/246177-combining-2-preg_replace/#findComment-1264291 Share on other sites More sharing options...
jcbones Posted September 1, 2011 Share Posted September 1, 2011 If you read the manual it will tell you that preg_replace will accept an array of strings as a pattern, and an array of strings as replacement. Link to comment https://forums.phpfreaks.com/topic/246177-combining-2-preg_replace/#findComment-1264351 Share on other sites More sharing options...
salathe Posted September 1, 2011 Share Posted September 1, 2011 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'])); Link to comment https://forums.phpfreaks.com/topic/246177-combining-2-preg_replace/#findComment-1264489 Share on other sites More sharing options...
dsp77 Posted September 2, 2011 Author Share Posted September 2, 2011 thank you salathe this is the code i was trying to achieve Link to comment https://forums.phpfreaks.com/topic/246177-combining-2-preg_replace/#findComment-1264635 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.