jackpf Posted May 6, 2009 Share Posted May 6, 2009 Good evening, I was just wondering how to make part of the regex optional. For example, this is my current regex: '/\[text width\=(.*?) height\=(.*?)\](.*?)\[\/text\]/isS' However, I'd like to make the width=(.*?) height=(.*?) optional. I've tried '/\[text( width\=(.*?))?( height\=(.*?))?\](.*?)\[\/text\]/isS' However, since my replacement is '<textarea style="overflow: auto;" cols="$1" rows="$2">$3</textarea>' If the height and width are ommited, it sets the contents as $1, so so it messes up my numbering. So yeah...anyone have any ideas? Thanks, Jack. Quote Link to comment https://forums.phpfreaks.com/topic/157139-solved-optional-regex/ Share on other sites More sharing options...
Ken2k7 Posted May 6, 2009 Share Posted May 6, 2009 preg_match('#\[text(\s*width=(?<width>\d+))?(\s*height=(?<height>\d+))?\](?<content>.*?)\[/text]#isS', $str, $match); Call them $match['width'], $match['height'] and $match['content']. Check if they're empty first. You shouldn't have mix ups there. Quote Link to comment https://forums.phpfreaks.com/topic/157139-solved-optional-regex/#findComment-827959 Share on other sites More sharing options...
jackpf Posted May 6, 2009 Author Share Posted May 6, 2009 I use preg_replace(), so...I'm not really sure how to sort it Quote Link to comment https://forums.phpfreaks.com/topic/157139-solved-optional-regex/#findComment-827981 Share on other sites More sharing options...
Ken2k7 Posted May 6, 2009 Share Posted May 6, 2009 Gah... preg_replace('#\[text(\s*width=(\d+))?(\s*height=(\d+))?\](.*?)\[/text]#isS', '<textarea cols="$2" rows="$4">$5</textarea>', $str); Quote Link to comment https://forums.phpfreaks.com/topic/157139-solved-optional-regex/#findComment-828007 Share on other sites More sharing options...
jackpf Posted May 6, 2009 Author Share Posted May 6, 2009 Brilliant. Cheers Quote Link to comment https://forums.phpfreaks.com/topic/157139-solved-optional-regex/#findComment-828050 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.