1

For the following code:

$string = "hello: Mister, Winterbottom";

$words = preg_split("/[\s,]+/", $string);
print_r ($words);

I get:

Array ( [0] => hello: [1] => Mister [2] => Winterbottom )

but I want the results to be:

Array ( [0] => hello [1] => Mister [2] => Winterbottom )

so that it will ignore the colon. How can I do it?

1
  • 2
    Use /[\s,:]+/. Or /\W+/ Commented Oct 17, 2016 at 16:55

2 Answers 2

1

If you need to expand your character class with :, just put it inside it and use

/[\s,:]+/

See its demo here. Or, just use /\W+/ to split with 1+ non-word characters.

$words = preg_split("/[\s,:]+/", $string);
print_r ($words);
// Or
print_r(preg_split("/\W+/", $string));

See the PHP demo

Sign up to request clarification or add additional context in comments.

Comments

0
$string = "hello: Mister, Winterbottom";

$words = preg_split("/[\s,]+/", $string);

$words[0] = rtrim($words[0],":");

print_r ($words);

2 Comments

Answers should have an explanation.
While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.