filoaman Posted July 2, 2015 Share Posted July 2, 2015 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 Quote Link to comment Share on other sites More sharing options...
Ch0cu3r Posted July 2, 2015 Share Posted July 2, 2015 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)); Quote Link to comment Share on other sites More sharing options...
filoaman Posted July 2, 2015 Author Share Posted July 2, 2015 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? Quote Link to comment Share on other sites More sharing options...
Solution Ch0cu3r Posted July 2, 2015 Solution Share Posted July 2, 2015 Seems to work ok when using the /u pattern modifier and changing a-z0-9+ to be \w+ New regex /(\w+|[^\s\w])/iu 1 Quote Link to comment Share on other sites More sharing options...
filoaman Posted July 2, 2015 Author Share Posted July 2, 2015 Yes it works fine now even with UTF8 characters! Thank you Ch0cu3r, i was on dead end... Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.