PHP: Best way to extract text within parenthesis?

后端 未结 8 1465
北海茫月
北海茫月 2020-11-28 06:11

What\'s the best/most efficient way to extract text set between parenthesis? Say I wanted to get the string \"text\" from the string \"ignore everything except this (text)\"

8条回答
  •  春和景丽
    2020-11-28 06:26

    function getStringsBetween($str, $start='[', $end=']', $with_from_to=true){
    $arr = [];
    $last_pos = 0;
    $last_pos = strpos($str, $start, $last_pos);
    while ($last_pos !== false) {
        $t = strpos($str, $end, $last_pos);
        $arr[] = ($with_from_to ? $start : '').substr($str, $last_pos + 1, $t - $last_pos - 1).($with_from_to ? $end : '');
        $last_pos = strpos($str, $start, $last_pos+1);
    }
    return $arr; }
    

    this is a little improvement to the previous answer that will return all patterns in array form:

    getStringsBetween('[T]his[] is [test] string [pattern]') will return:

提交回复
热议问题