gunjanamit Posted July 21, 2012 Share Posted July 21, 2012 Hi, I am looking for regex to extract following words from text: The word which comes after "Replaced" means Replaced disk Replaced floppy Replaced memory Please suggest the regex for it. Thanks! Quote Link to comment https://forums.phpfreaks.com/topic/266045-regex-problem/ Share on other sites More sharing options...
jazzman1 Posted July 21, 2012 Share Posted July 21, 2012 Take a look at this example, or..... you want to be something else ? <?php $pattern = '/(?<=Replaced )(?=(\w+))/'; $str = 'Replaced disk, Replaced floppy, Replaced memory'; if(preg_match_all($pattern, $str,$matches)){ echo '<pre>'.print_r($matches[1], true).'</pre>'; } else { echo 'No match'; } ?> Quote Link to comment https://forums.phpfreaks.com/topic/266045-regex-problem/#findComment-1363353 Share on other sites More sharing options...
requinix Posted July 22, 2012 Share Posted July 22, 2012 Or the simpler, non-lookaround version of just Replaced (\w+) Quote Link to comment https://forums.phpfreaks.com/topic/266045-regex-problem/#findComment-1363408 Share on other sites More sharing options...
gunjanamit Posted July 22, 2012 Author Share Posted July 22, 2012 Thanks guys I tried Replaced (\w+) but it is working when "replaced" is a first word of text. But if the word is coming in middle of text then regex is not working. Please suggest !!! Quote Link to comment https://forums.phpfreaks.com/topic/266045-regex-problem/#findComment-1363502 Share on other sites More sharing options...
jazzman1 Posted July 22, 2012 Share Posted July 22, 2012 What do you mean ? Did you loop it ? For example: $newItems = array('computer','RAM', 'CD Rom'); $pattern = '/(?<=Replaced )(?=(\w+))/'; $str = 'Replaced disk, Replaced floppy, Replaced memory'; if(preg_match_all($pattern, $str,$matches)){ for($i=0;$i<count($newItems);$i++){ $matches[1][$i] = $newItems[$i]; } echo '<pre>'.print_r($matches[1], true).'</pre>'; } Quote Link to comment https://forums.phpfreaks.com/topic/266045-regex-problem/#findComment-1363550 Share on other sites More sharing options...
requinix Posted July 22, 2012 Share Posted July 22, 2012 But if the word is coming in middle of text then regex is not working. Case matters. Do you perhaps want it to find "replaced" too? Quote Link to comment https://forums.phpfreaks.com/topic/266045-regex-problem/#findComment-1363575 Share on other sites More sharing options...
gunjanamit Posted July 23, 2012 Author Share Posted July 23, 2012 yes.. it is case sensitive I have 2 records 1) Replaced hard disk immediately - Regex Working 2) I have to replace the hard disk - Regex not Working Kindly suggest!!! Quote Link to comment https://forums.phpfreaks.com/topic/266045-regex-problem/#findComment-1363610 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.