domenico Posted November 15, 2008 Share Posted November 15, 2008 I have this string: $string="bla bla sentence (one) bla sentence (two) (three) bla bla bla (four)"; i would like to extract (one) (two) (three) (four) and put them in an array. Someone can show me some example with eregi() or non posix functions? Link to comment https://forums.phpfreaks.com/topic/132808-solved-how-to-extrapolate-words-from-a-string/ Share on other sites More sharing options...
SuperBlue Posted November 15, 2008 Share Posted November 15, 2008 Try something like the below. <?php $string = 'one and some text two and some text three and some text four and some text'; // The input string $arr = array('one', 'two', 'three', 'four'); // Words to find foreach ($arr as &$word) { $RT_Code = '/.*(' . $word . ').*/s'; $WT_Code = '$1' . '<br>'; echo preg_replace($RT_Code, $WT_Code, $string); } ?> Let me quickly cover the expression /.*(' . $word . ').*/s The (dot) matches any character, while the star means that either there is something, in front of, or after the word we are looking for. If i used a plus sign "+", then it would only match words that had something before or after them. The parentheses remembers the match, so we can access this through "$1" later, which where done on the next line. Finally the "s" modifier at the end makes the (dot) include newlines. You can use the "i" modifier as well to make an case insensitive search. Link to comment https://forums.phpfreaks.com/topic/132808-solved-how-to-extrapolate-words-from-a-string/#findComment-690718 Share on other sites More sharing options...
ddrudik Posted November 15, 2008 Share Posted November 15, 2008 If you want to just match items in non-nested paired parens groups: Raw Match Pattern: (?<=\()[^)]*(?=\)) PHP Code Example: <?php $sourcestring="your source string"; preg_match_all('/(?<=\()[^)]*(?=\))/',$sourcestring,$matches); echo "<pre>".print_r($matches,true); ?> $matches Array: ( [0] => Array ( [0] => one [1] => two [2] => three [3] => four ) ) If you want to capture the parens as well: preg_match_all('/\([^)]*\)/',$sourcestring,$matches); Link to comment https://forums.phpfreaks.com/topic/132808-solved-how-to-extrapolate-words-from-a-string/#findComment-690774 Share on other sites More sharing options...
domenico Posted November 16, 2008 Author Share Posted November 16, 2008 Perfect! it works very well, thank you Link to comment https://forums.phpfreaks.com/topic/132808-solved-how-to-extrapolate-words-from-a-string/#findComment-691193 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.