PHP在字符串之间获取字符串

时间:2018-07-18 18:05:59

标签: php string

我想获取以下PHP代码的// begin和// end之间的字符串 我曾经考虑过使用正则表达式,但是我不知道如何提取目标字符串。任何建议都会被采纳。

<?php
$test='
//pool test area
//begin

var out0=0;

//end
// end pool test area

';
?>

1 个答案:

答案 0 :(得分:0)

您可以使用正则表达式或将字符串转换为数组并遍历新创建的数组,请尝试以下操作:

<?php

$test = '
//pool test area
//begin

var out0=0;

//end
// end pool test area

';

function getString($testString, $start, $end) 
{
$arr = explode($start, $testString);   
foreach ($arr as $item) {     
    if (strpos($item, $end) != false){
        $aResult[] = substr($item, 0, strpos($item, $end));        
    }
  }
  return implode("", $aResult);    
}

echo getString($test, "//begin", "//end");

输出:

var out0=0;
相关问题