gerkintrigg Posted April 30, 2007 Share Posted April 30, 2007 I'm writing a chat robot and need to explode a string, using either a space, full-stop (period), comma, question-mark etc. I'm using: $words=explode(" ", $search_phrase); and just need other variables to split it by. Thanks. Link to comment https://forums.phpfreaks.com/topic/49329-exploding-strings/ Share on other sites More sharing options...
Wildbug Posted April 30, 2007 Share Posted April 30, 2007 preg_split('/\s+|[,?!]/',$string); There might be another, non-preg function, but I don't know it offhand. Link to comment https://forums.phpfreaks.com/topic/49329-exploding-strings/#findComment-241737 Share on other sites More sharing options...
obsidian Posted April 30, 2007 Share Posted April 30, 2007 preg_split('/\s+|[,?!]/',$string); There might be another, non-preg function, but I don't know it offhand. I'll second that suggestion. The only thing you'll have to watch out for is the fact that this will split all words on to separate lines. So, even if you have something like an email address that contains one of your punctuations for which you are searching, you'll split on it: <?php $string = "[email protected] is my email!"; $words = preg_split('|[\s,?!.]|', $string); // results in array('i', 'the', 'bomb@mydomain', 'co', 'uk') ?> You may be better off just doing a preg_match_all() on all word boundaries: <?php preg_match_all('|\b(.+?)\b|', $string, $words, PREG_PATTERN_ORDER); ?> Hope this helps. Link to comment https://forums.phpfreaks.com/topic/49329-exploding-strings/#findComment-241742 Share on other sites More sharing options...
gerkintrigg Posted April 30, 2007 Author Share Posted April 30, 2007 brilliant, thanks! Link to comment https://forums.phpfreaks.com/topic/49329-exploding-strings/#findComment-241750 Share on other sites More sharing options...
The Little Guy Posted April 30, 2007 Share Posted April 30, 2007 <?php $sometext = "This is a senten-ce. Do you like it?"; $arrays = preg_split("/ |-/",$sometext); Link to comment https://forums.phpfreaks.com/topic/49329-exploding-strings/#findComment-241752 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.