esdaniel Posted October 26, 2008 Share Posted October 26, 2008 A cry for help... Sample text: The cat sat on the [[straw|mat]]. The cat hoped he would jump through the [[windows]] and catch the [[feathered variety|bird on the branch]]. The regex pattern I'm struggling to put together would match all text between "|" and "]]" or where there is no "|" then all text between "[[" and "]]", as per the text above this regex would then match the following strings: "mat" "windows" "bird on the branch" Allowing me to replace the text between and including [[ and ]] with the strings in the match. Any guidance/help would be greatly appreciated. Quote Link to comment https://forums.phpfreaks.com/topic/130173-solved-matchreplace-2-patterns-in-one-pass/ Share on other sites More sharing options...
discomatt Posted October 26, 2008 Share Posted October 26, 2008 I think i see what you mean... try this guy <pre><?php $subject = 'The cat sat on the [[straw|mat]]. The cat hoped he would jump through the [[windows]] and catch the [[feathered variety|bird on the branch]].'; $array = getValues( $subject ); print_r( $array ); function getValues( $input ) { $regex = '/\[\[([^|\]]++)(?:\|([^\]]++)){0,1}/'; if( preg_match_all($regex, $input, $matches, PREG_SET_ORDER) < 1 ) return array(); $return = array(); foreach( $matches as $m ) { if( isset($m[2]) === FALSE ) $return[] = $m[1]; else $return[] = $m[2]; } return $return; } ?></pre> Quote Link to comment https://forums.phpfreaks.com/topic/130173-solved-matchreplace-2-patterns-in-one-pass/#findComment-675107 Share on other sites More sharing options...
effigy Posted October 27, 2008 Share Posted October 27, 2008 <pre> <?php $subject = 'The cat sat on the [[straw|mat]]. The cat hoped he would jump through the [[windows]] and catch the [[feathered variety|bird on the branch]].'; preg_match_all( '%\[\[(?:[^]|]+\|)?([^]]+)\]\]%', $subject, $matches ); $matches = $matches[1]; print_r($matches); ?> </pre> Quote Link to comment https://forums.phpfreaks.com/topic/130173-solved-matchreplace-2-patterns-in-one-pass/#findComment-675608 Share on other sites More sharing options...
esdaniel Posted October 29, 2008 Author Share Posted October 29, 2008 Thank you Discomatt and Effigy... the second response is ideal as it allows me to use str_replace and makes the resulting code much more eloquent/readable in that I don't have to code-around varying array sizes as per discomatt's initial solution i.e. preg_match_all('%\[\[(?:[^]|]+\|)?([^]]+)\]\]%',$content,$replace); $content = str_replace($replace[0],$replace[1],$content); I'm very pleased to have found this forum and hope I can give something back in the near future. Quote Link to comment https://forums.phpfreaks.com/topic/130173-solved-matchreplace-2-patterns-in-one-pass/#findComment-677194 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.