简体   繁体   English

如果是,则使用正则表达式-如何编写条件

[英]If, then, else regex - How to write the Condition

Trying to capture name= and value= US or NONE (if selected="selected" not included). 尝试捕获name =和value = US或NONE(如果不包括selected =“ selected”)。 Given the following (part of a larger $page): 给定以下内容(较大的$ page的一部分):

$page = '
<select name="country" ><option value="NONE">Select One</option>    
<option value="AE">UNITED ARAB EMIRATES</option>
<option value="GB">UNITED KINGDOM</option>
<option value="US" selected="selected">UNITED STATES</option>
<option value="UY">URUGUAY</option>
<option value="UZ">UZBEKISTAN</option>
<option value="ZW">ZIMBABWE</option></select>';

Edit 1 This pattern won't pick up NONE if none of the options are selected. 编辑1如果未选择任何选项,则此模式将不显示NONE。

$pattern = '/select name="([a-zA-Z]*)"\s?>[\w\W]*value="([A-Z]{2,4})"(selected="selected">)?/'

So, I'm looking for a pattern that will. 因此,我正在寻找一种可能的模式。

The syntax for the if, then, else regex in php is: php中if,then,else regex的语法为:

(if 'selected=' found) then find pattern     | else find this pattern
  (if condition)        then regex           |   else regex
(?(?=.*selected=)value="([A-Z]+)"\s+selected=|value="(NONE)">)

The .* is necessary for the condition to be true. .*是使条件为真所必需的。

Does it have to be one regex ? 是否必须是一个正则表达式?

I would recommend splitting it up this way: 我建议以这种方式将其拆分:

  • match the element 匹配元素
  • tryMatch with the "selected" attribute tryMatch与“选定”属性
  • proceed according to results - I'm not sure what the logic is as don't quite undestand from your description when you want which value. 根据结果​​进行操作-我不确定逻辑是什么,因为当您想要哪个值时,并不能完全理解您的描述。 But either way it should be easy to get either value or name attributes. 但是无论采用哪种方式,都应该容易获得值或名称属性。

The benefit of this approach is that you are working on a part of the html code and it's far less error prone. 这种方法的好处是您正在处理html代码的一部分,而且出错的可能性要小得多。

EDIT: 编辑:

BTW: how do you know it never evaluates to true ? 顺便说一句:你怎么知道它永远不会评估为真? It seems to work as intended (ie matching 'select' or 'select name="country") here 它似乎按预期工作(即匹配“选择”或“选择名称=“ country”)
http://www.pagecolumn.com/tool/pregtest.htm http://www.pagecolumn.com/tool/pregtest.htm

(you need to escape the quotes (?(?=selected=\\"selected\\")select|select name=\\"([a-zA-Z]*)\\") to use it there) (您需要使用引号(?(?=selected=\\"selected\\")select|select name=\\"([a-zA-Z]*)\\")进行转义)

EDIT2 EDIT2

I still won't be able to help you with if then else, but based on your explanation I can suggest this: 我仍然无法为您提供帮助,但是根据您的解释,我可以建议您:

<select name="([^"]*)".*?(?!</select>)<option value="[^"]*" selected="selected"|<select name="([^"]*)"\s*>\s*<option value="([^"]*)">
  • so, tryMatch selected, if it fails match just the first option 因此,请选择tryMatch,如果失败则仅匹配第一个选项

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM