开发者

Regex Optional Matches

I'm trying to match two types of strings using the preg_match function in PHP which could be the following.

In the third one above, I only want the "mything" and "newthing" so everything that comes after the third part is just some optional text the user could add. Ideally out of the regex would come in the cases of above;

  • 'mything', 'newthing'
  • 'onething'
  • 'mything', 'newthing'

The patterns should match a-zA-Z0-9 if possible :-)

My regex is terrible, so any help would be appreciated!

Thanks in advanced.


Assuming you're talking about _ deliminated text:

$regex = '/^_([a-zA-Z0-9]+)(|_to_([a-zA-Z0-9]+).*)$/';

$string = '_mything_to_newthing_and_some_stuff';
preg_match($regex, $string, $match);
$match = array(
    0 => '_mything_to_newthing_and_some_stuff',
    1 => 'mything',
    2 => '_to_newthing_and_some_stuff',
    3 => 'newthing',
);

As far as anything farther, please provide more details and better sample text/output

Edit: You could always just use explode:

$parts = explode('_', $string);
$parts = array(
    0 => '',
    1 => 'mything',
    2 => 'to',
    3 => 'newthing',
    4 => 'and',
    5 => 'some',
    6 => 'stuff',
);

As long as the format is consistent, it should work well...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜