2011-01-21 197 views
1

我試圖在PHP中使用preg_match函數來匹配兩種類型的字符串,可能如下。正則表達式可選匹配

  • '_mything_to_newthing'
  • '_onething'
  • '_mything_to_newthing_and_some_stuff'

在第三個以上,我只希望 「mything」 和 「newthing」 後自帶所以一切第三部分只是用戶可以添加的一些可選文本。理想情況下,正則表達式會出現在上面的情況中;

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

的模式應該儘可能匹配-ZA-Z0-9: - )

我的正則表達式是可怕的,所以任何幫助將不勝感激!

謝謝先進。

回答

1

假設你正在談論_ deliminated文本:

$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', 
); 

至於什麼更遠,請提供更多的細節和更好的示例文本/輸出

編輯:你總是可以只使用explode

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

只要格式一致,它應該工作我們ll ...

+0

謝謝!你知道..我從來沒有想過它是`_`分隔文本!我可能只是使用`explode()`;) – tarnfeld 2011-01-21 23:39:56