开发者

Strip non alphanumeric characters and limit string to two words

开发者 https://www.devze.com 2023-02-12 03:57 出处:网络
I\'m trying to strip non-alphanumeric characters from a string and limit the string to two words. i.e:

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($w开发者_Go百科ords,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


First normalize the string by removing excess space as follows:

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

Then do the rest, it will work.


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

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

Do this immediately before your explode.


$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
?>
0

精彩评论

暂无评论...
验证码 换一张
取 消