0

I'm trying to strip non-alphanumeric characters from a string and limit the string to two words. i.e:

foo bar baz    => foo-bar
boo   * test   => boo-test
te%st_foo      => test-foo

So far I've got this:

$term = preg_replace('/[^A-Za-z0-9 ]/', '', $term);
$words = explode(" ", $term);
$generated = strtolower(implode(" ",array_splice($words,0,2)));
$term = preg_replace('!\s+!', '-', $term);

But going wrong somewhere, these are snippets I've just snapped together to try and get the results I'm after.

The problem is really if there is more than 1 space in a string etc.

Help appreciated :)

Thanks

John
  • 1
  • 1
  • `foo bar baz => foo-bar`? Can you explain this? – fredley Feb 21 '11 at 15:30
  • This seems to be a possible duplicate of [Regular Expression regex to validate input: Two words with a space between](http://stackoverflow.com/questions/5060895/regular-expression-regex-to-validate-input-two-words-with-a-space-between) – David Thomas Feb 21 '11 at 15:31
  • @fredley I want to limit the output string to only two words, word1-word2 – John Feb 21 '11 at 15:32

3 Answers3

1

First normalize the string by removing excess space as follows:

preg_replace('/[ ]+/', ' ', $term);

Then do the rest, it will work.

adarshr
  • 61,315
  • 23
  • 138
  • 167
0

For reducing multiple [white]spaces to a single space use:

$string = preg_replace("/[ \t\n\r]+/", " ", $string);

Do this immediately before your explode.

fredley
  • 32,953
  • 42
  • 145
  • 236
0
$str = preg_replace('/[^a-z]+/is', '-', $str);
$str = trim(str_replace('--', '-', $str), '-');
// now we have array of words
$str = explode('-', $str);
$str = $str[0].'-'.$str[1];

UPD:

<?php
    $str = 'foo&*^%#*$&@^     bar          asjdhakhsgd';
    $str = preg_replace('/[^a-z]+/is', '-', $str);
    $str = trim(str_replace('--', '-', $str), '-');
    $str = explode('-', $str);
    $str = $str[0].'-'.$str[1];

    echo $str; // foo-bar
?>
delphist
  • 4,409
  • 1
  • 22
  • 22