1

所以我有这个脚本可以在更大的字符串中提取给定的字符串:

function get_string($string, $start, $end){
 $string = " ".$string;
 $pos = strpos($string,$start);
 if ($pos == 0) return "";
 $pos += strlen($start);
 $len = strpos($string,$end,$pos) - $pos;
 return substr($string,$pos,$len);
}

所以这是字符串:

$string= '<b>Sample Sample</b> <b>Sample2 Sample2</b>';

$output = get_string($string, '<b>','</b>');

echo $output;

我真的需要一些帮助,因为我没有想法。现在,当我回声时,$output我得到

Sample Sample

我想做一个同时显示两者的更改:

Sample Sample 

Sample2 Sample2

你们中的任何人有任何想法如何修改函数并使其输出某种结果数组 $output[0]$output[1]

提前谢谢你,祝你有个美好的一天。

4

5 回答 5

2

您可能会发现这更简单,也更容易理解:

function get_string($string, $start, $end) {
    $start = preg_quote($start, '|');
    $end = preg_quote($end, '|');
    $matches = preg_match_all('|'.$start.'([^<]*)'.$end.'|i', $string, $output);
    return $matches > 0
        ? $output[1]
        : array();
}        

$string= '<b>Sample Sample</b> <b>Sample2 Sample2</b>';
$output = get_string($string, '<b>', '</b>');    
print_r($output);

输出:

Array
(
    [0] => Sample Sample
    [1] => Sample2 Sample2
)
于 2012-09-16T00:40:55.187 回答
2

修改您的函数,以便只要while, 该函数为您提供一个字符串,将其添加到数组中,然后在字符串末尾再次运行该函数。

编辑:

如果您碰巧想自己尝试,不想拼出正确的解决方案。这是一种方法,可以得到你想要的。我试图对您的原始帖子进行尽可能少的更改:

function get_string($string, $start, $end){
    $found = array();
    $pos = 0;
    while( true )
    {
        $pos = strpos($string, $start, $pos);
        if ($pos === false) { // Zero is not exactly equal to false...
            return $found;
        }
        $pos += strlen($start);
        $len = strpos($string, $end, $pos) - $pos;
        $found[] = substr($string, $pos, $len);
    }
}

$string = '<b>Sample Sample</b> <b>Sample2 Sample2</b>';

$output = get_string($string, '<b>','</b>');

var_dump( $output );

输出:

array(2) {
  [0]=>
  string(13) "Sample Sample"
  [1]=>
  string(15) "Sample2 Sample2"
}
于 2012-09-16T00:41:23.410 回答
0

查看上面的示例,字符串包含 b 标签,它们是 HTML 标签。

PHP 库定义了一个名为 strip_tags 的函数,它将从字符串中去除 HTML 标记。

因此,您的输出字符串将生成纯文本字符串,并从字符串中删除所有 HTML 标记。

于 2012-09-16T00:50:55.760 回答
0

我讨厌不得不使用正则表达式,所以这里有一个非膨胀软件版本:

function get_string($string, $start, $end){
 $results = array();
 $pos = 0;
 do {
   $pos = strpos($string,$start,$pos);
   if($pos === FALSE) break;
   $pos += strlen($start);
   $len = strpos($string,$end,$pos) - $pos;
   $results[] = substr($string,$pos,$len);
   $pos = $pos + $len;
 } while(1);
 return $results;
}

$string= '<b>Sample Sample</b> <b>Sample2 Sample2</b>';

$output = get_string($string, '<b>','</b>');

var_dump($output);

输出:

array(2) { [0]=> string(13) "Sample Sample" [1]=> string(15) "Sample2 Sample2" } 
于 2012-09-16T00:54:18.607 回答
0

这可以帮助....

function get_string($string, $start, $end = null) {
     $str = "";
     if ($end == null) {
         $end = strlen($string);
     }
     if ($end < $start) {
         return $string;
     }
     while ($start < $end) {
          $str .=$string[$start];
          $start++;
     }
     return $str;
 }
于 2015-06-17T14:11:24.453 回答