drfls28608 2015-11-11 10:09
浏览 26
已采纳

php Regular Expression返回特定的字符串

Let us say, I want to return a name:

$re = "/(name is )[a-z- ]*( )/i";
$str = "My name is John ";

preg_match($re, $str, $matches);

print_r($matches);

The result is:

Array
(
    [0] => name is John 
    [1] => name is 
    [2] =>  
)

Well, let's see this:

$string = "My name is John and I like Ice-cream";
$pattern = "My name is $1 and I like $2";

With this I get: Array

(
    [0] => name is John and I like Ice-cream 
    [1] => name is 
    [2] =>  and I like 
    [3] =>  
)

which is more or less the same string I passed.

What I am looking for is to compare and extract the variables so that I could use them as variable $1 and $2 or anything like this works.

Or maybe a method that returns an associate array or those items like:

Array("1" => "John" , "2" => "Ice-cream")

Any workaround or ideas are highly appreciated as long as they work in the way I asked above.

  • 写回答

2条回答 默认 最新

  • doujuxin7392 2015-11-11 10:17
    关注
    $str = 'My name is John and I like Ice-cream';
    $re = '/My name is (\S+) and I like (\S+)/';
    preg_match($re, $str, $matches);
    
    print_r($matches);
    

    returns

    Array
    (
        [0] => My name is John and I like Ice-cream
        [1] => John
        [2] => Ice-cream
    )
    

    \\S matches non-whitespace.

    Change it to . to match anything, which will work as far as the other strings in the pattern ("My name is " and " I like ") are fixed.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?