0

Please I have this string :

$s = "Cannes (06150-06400), Limoges (87000-87100-87280), 06000, Paris";

I want to store only words in an array, so I tried this :

$villes = explode(',', preg_replace('#\(([0-9\-]*)\)#', '', $s));

But in result I get this array :

array(4) {
          [0]=>
             string(7) "Cannes "
          [1]=>
             string(9) " Limoges "
          [2]=>
             string(7) "  06000" // This shouldn't be displayed in the array
          [3]=>
             string(6) " Paris"
         }

Please how could I modify the regex to get it work as I wish. Thanks.

1
  • what about str_word_count($string, 1)? Commented Nov 29, 2016 at 9:46

4 Answers 4

3

Try:

<?php
$s = "Cannes (06150-06400), Limoges (87000-87100-87280), 06000, Paris";
preg_match_all("/[a-zA-Z]+/", $s, $villes);
var_dump($villes[0]);
?>

For single word names. Var dump:

array(3) {
  [0]=>
  string(6) "Cannes"
  [1]=>
  string(7) "Limoges"
  [2]=>
  string(5) "Paris"
}
Sign up to request clarification or add additional context in comments.

Comments

1

Try

$arr = preg_split('/\s*\(?[\d\-\s]*\)?\s*,\s*/', $s, -1, PREG_SPLIT_NO_EMPTY);
var_dump($arr);

Output

array(3) {
  [0] =>
  string(6) "Cannes"
  [1] =>
  string(7) "Limoges"
  [2] =>
  string(5) "Paris"
}

Comments

0
preg_match( '/[a-zA-Z\-\']+/', $s, $words );
var_dump( $words[0] );

Comments

0

you can use array for result.

$arr=explode(' ' , $s);
print_r($arr);

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.