Jump to content

Complex (?) explode data from a string to array


filoaman

Recommended Posts

Hi coders

I have a string contain simple text, numbers and "special characters" (e.g. commas, points, quotes etc.)

$string="This is, the text of my String!!! Contain numbers like 200 and other items like %.";

What i'd like to do is explode in array like this

$elements=array('This', 'is', ''', 'the', 'text', 'of', 'my', 'String','!', '!, '!', 'Contain', 'numbers', 'like', '200', 'and', 'other', 'items', 'like', '%', '.');

I try several methods and i explode some of the elemnts like whole words, or words and numbes but i'm unable to find a way to explode the "special characters' the way i like.

 

Any ideas?

 

Thank you in advance

 

 

Try using regex

$text = 'This is, the text of my String!!! Contain numbers like 200 and other items like %.';

// matches, whole words and number, and splits on non space/word characters
preg_match_all('/(([a-z0-9]+)|([^\s\w]))/i', $text, $matches);
// see what it matches
printf('<pre>%s</pre>', print_r($matches[0], 1));

Yes it works fine. Thank you Ch0cu3r

The problem is that many of the strings i'd like to explode contain UTF-8 characters and in this case doesn't work correctly.

 

If i try, for example to explode a string like this

$string="This is, the text of my Investigação String!!! Contain ocasião numbers like 200 and other items like %.";

doesn't work correctly.

 

I search for a solution and the only one i can find was to add a (*UTF8) before the regex, but unfortunately without succes...

 

Any ideas?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.