Jump to content

Complex (?) explode data from a string to array


filoaman
Go to solution Solved by Ch0cu3r,

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

 

 

Link to comment
Share on other sites

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));
Link to comment
Share on other sites

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?

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.