duanlei4759 2016-10-04 08:55
浏览 113
已采纳

php - 在字符串中查找匹配项

I'm trying to work out how to find a match in a string. I'm looking for a match on any of the following - = ? [] ~ # ! 0 - 9 A-Z a-z and I need to know what its matched on .

Eg: matched on !, or matched on = and # and ?

Normally I'd use this:

$a = 'How are you?';

if (strpos($a, 'are') !== false) {
    echo 'true';
}

However I'm not sure how to do that so it looks up the characters needed. Also where I may have [], It could be [] or [xxxx] where xxxx could be any number of alpha numeric characters.

I need to match and any of the characters listed, return the characters so I know what was matched and if the [] contain any value return that as well.

Eg:

$a = 'DeviceLocation[West12]'; Would return: $match = '[]'; $match_val= 'West12';

$a = '#=Device'; Would return:$match = '#,=';

$a= '?[1234]=#Martin'; Would return: $match = '?, [], =, #'; $match_val= '1234';

Can any one advise how I can do this. Thanks

  • 写回答

4条回答 默认 最新

  • duanguzhong5776 2016-10-04 10:44
    关注

    Well, that requirements are a bit vague, but that is what I deduced:

    1) if there is an alphanumeric string inside square brackets get it as a separate value
    2) all other mentioned chars should be matched one by one and then imploded.

    You may use the following regex to get the values you need:

    $re = '@\[([a-zA-Z0-9]+)\]|[][=?~#!]@';
    

    Details:

    • \[ - a [
    • ([a-zA-Z0-9]+) - Group 1 value capturing 1 or more alphanumeric symbols
    • \] - a closing ]
    • | - or
    • [][=?~#!] - a single char, one of the defined chars in the set.

    See the regex demo. The most important here is the code that gets the matches (feel free to adapt):

    $re = '@\[([a-zA-Z0-9]+)\]|[][=?~#!]@';
    $strs =array('DeviceLocation[West12]', '#=Device', '?[1234]=#Martin');
    
    foreach ($strs as $str) {
        preg_match_all($re, $str, $matches, PREG_SET_ORDER);
        $results = array();
        $match_val = "";
        foreach ($matches as $m) {
            if (!empty($m[1])) {
                $match_val = trim($m[1], "[]");
                array_push($results, "[]");
            } else {
                array_push($results, $m[0]);
            } 
        }
        echo "Value: " . $match_val . "
    ";
        echo "Symbols: " . implode(", ", $results);
        echo "
    -----
    ";
    }
    

    See the PHP demo

    Output:

    Value: West12
    Symbols: []
    -----
    Value: 
    Symbols: #, =
    -----
    Value: 1234
    Symbols: ?, [], =, #
    -----
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法