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 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据