开发者

php search function using wildcards

开发者 https://www.devze.com 2023-01-14 16:44 出处:网络
This question is nearly identicle to : Php search string (with wildcards), but will be arranged a little differently. I had a hard time understanding the proposed solutions to make my own out of them

This question is nearly identicle to : Php search string (with wildcards), but will be arranged a little differently. I had a hard time understanding the proposed solutions to make my own out of them . Maybe you guys can help?

I have a start string and an end string which I use to sandwich strings of interest.

This is the function I'm currently using for this:

function get_string_between($string, $开发者_运维知识库start, $end)
{
     $string = " ".$string;
     $ini = strpos($string,$start);
     if ($ini == 0) return "";
     $ini += strlen($start);   
     $len = strpos($string,$end,$ini) - $ini;
     return substr($string,$ini,$len);
}

Sometimes my beginning strings need to have wildcards in them to account for a dynamic part of a template

for example I would need this to be my begin code variable:

$begin_code = "id='%wildcard%' class='sailors_assistant_%wildcard%'>";

and edit my original function above to detect %wildcard%(s) and account for them when using their sandwich search-n-grabs.

Any advise?


The easiest way would be to use a regular expression:

function get_string_between($string, $start, $end) {
    $start = str_replace("%wildcard%", ".*?", preg_quote($start, "/");
    $end = str_replace("%wildcard%", ".*?", preg_quote($end, "/");
    $regex = "/$start(.*?)$end/";
    if (preg_match($regex, $string, $matches))
        return $matches[1];
    else
        return false;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号