2

What's best performing script to replace certain characters with a maximum of one other character?

For instance, I need to replace all spaces () and commas (,) with plus signs (+) but no more than one plus sign at a time

So: the,quick, brown fox jumped, over the,, lazy, dog

Would become: the+quick+brown+fox+jumped+over+the+lazy+dog

Kyle Cureau
  • 19,028
  • 23
  • 75
  • 104
  • What you're asking for is called "slug". You may find some ready snippets here and there: http://stackoverflow.com/questions/5305879/automatic-clean-and-seo-friendly-url-slugs, http://code.google.com/p/php-slugs/ – Taz Apr 17 '12 at 20:34

2 Answers2

7

I would use a regular expression for this:

$text = 'the,quick, brown fox jumped, over the,, lazy, dog';
$newText = preg_replace('/[ ,+]+/', '+', $text);
FtDRbwLXw6
  • 27,774
  • 13
  • 70
  • 107
  • To have it look a little bit nicer take `\s` for a whitespace :) Not mandatory, but I think it's always a bit about make up too – dan-lee Apr 17 '12 at 20:31
  • @DanLee: Yeah, he probably meant whitespace characters, but he only said spaces, so I didn't use `\s` in case he didn't want tabs, newlines, etc. being replaced as well. – FtDRbwLXw6 Apr 17 '12 at 20:35
  • Okay my thoughts were that `\s` covers more than a plain white space (some ord values etc). And I dont think that `\s` covers tabs (`\t`) and new lines (`\n` or `\r\n`). But your argument is valid so this should do the job. – dan-lee Apr 17 '12 at 20:37
  • @DanLee: In PCRE, `\s` covers spaces, tabs `\t`, newlines `\n`, carriage returns `\r`, vertical tabs `\v`, and form feeds `\f`. In PHP's implementation, vertical tabs `\v` don't seem to be matched by `\s` (not sure if this is a bug or intentional omission), but the others are. – FtDRbwLXw6 Apr 17 '12 at 21:00
  • If anyone cares, here's an explanation of whitespace classification: http://php.net/manual/en/reference.pcre.pattern.differences.php. It looks like the omission of `\v` from being matched by `\s` is intentional and it explains why. – FtDRbwLXw6 Apr 17 '12 at 21:07
2
<?php
echo preg_replace('/[, ]+/', '+', 'the,quick, brown fox jumped, over the,, lazy, dog') . PHP_EOL;
sfx
  • 287
  • 3
  • 8