Jump to content

[SOLVED] Optional Regex


jackpf

Recommended Posts

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.

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.