Searching and extracting from a String using regex in PHP

This question already has an answer here:

  • How do I check if a string contains a specific word? 37 answers

  • I am sure you're going to be able to figure out how to insert user input into variables $start or $end – just in case: ask them if they want the input string at the beginning or at the end, and based on the answer, save the string to search in to either $start or $end .

    $string = "Ford Chevrolet Dodge Chrysler";
    $start = "";
    $end = "let";
    
    if(!empty($start))
        preg_match_all("#" . $start . "w+#", $string, $matches);
    elseif(!empty($end))
        preg_match_all("#w+" . $end ."#", $string, $matches);
    else
        die("Nothing has been set!");
    
    print_r($matches);
    

    This is the case implemented for all the words ending with a let in your example string. Bear in mind the regex is only going to match word characters. If you're going to get more complicated strings, maybe another solution should be created.


    To simply echo all the matches, use foreach loop like this instead of the print_r function:

    if(!empty($matches))
    {
        foreach($matches as $match)
            echo $match . "<br>";
    }
    else
        die("Nothing matched!");
    
    链接地址: http://www.djcxy.com/p/13136.html

    上一篇: 在字符串中查找相关字符串

    下一篇: 使用PHP中的正则表达式在String中搜索和提取