1

I want to split a string in to array. I want that the words and the metacharacters separated in an array. Like this:

$string = 'This is a string? Or an array?';

i want:

array[0] = 'This',
array[1] = 'is',
array[2] = 'a',
array[3] = 'string',
array[4] = '?',
array[5] = 'Or',
array[6] = 'etc';

I know that must use preg_split. But i can manage only selecting strings or no string. And i searched for on the internet but i only could found examples without the metacharacters.
I hope that some one know the answer, because i its in the delimiter of the preg_spilt.

Thank you for your time.

chris85
  • 23,846
  • 7
  • 34
  • 51
Overste
  • 111
  • 2
  • 4
  • What's a metacharacter? Do you mean punctuation marks? – WillardSolutions Jan 22 '17 at 15:13
  • thank you for your respons. Yes i want all the: punctuation marks questions marks, etc. Also in an array. I have to make a dictation program that checks is the words are correct spelled. And that punctuation marks are on the right position. – Overste Jan 22 '17 at 15:13

2 Answers2

3

You could do:

 $string= 'This is a string? Or an array?';
 $array = array_filter(array_map('trim',preg_split("/\b/", $string)));
 print_r($array);

Prints:

Array
(
    [1] => This
    [3] => is
    [5] => a
    [7] => string
    [8] => ?
    [9] => Or
    [11] => an
    [13] => array
    [14] => ?
)

What's going on here is you're splitting on \b which is a word boundary. The reason for the trimming and filtering is that this also matches whitespaces.

apokryfos
  • 38,771
  • 9
  • 70
  • 114
  • 1
    You can simplify this a bit by using `array_filter(preg_split("/\s|\b/", $string);`, which also splits on whitespace characters. – squirl Jan 22 '17 at 16:08
0

You can try with explode() too:

$string= 'This is a string? Or an array?';
$replaced_string = str_replace("?", " ?", $string); 
$array = explode(" ", $replaced_string);

for ($i = 0; $i < count($array); $i++){
    echo $array[$i]."<br>";
}

The result is:

This<br>
is<br>
a<br>
string<br>
?<br>
Or<br>
an<br>
array<br>
?

Or do this:

for ($i = 0; $i < count($array); $i++){
    echo 'array['.$i.']='.$array[$i]."<br>";
}

The result is:

array[0]=This<br>
array[1]=is<br>
array[2]=a<br>
array[3]=string<br>
array[4]=?<br>
array[5]=Or<br>
array[6]=an<br>
array[7]=array<br>
array[8]=?
Jaymin Panchal
  • 2,797
  • 2
  • 27
  • 31