我有一个名为$ post的字符串(例如),其中包含数据。我想删除行直到第一个“TEXT”(我不知道会有多少标签,所以没有确切的行可行)。我还想删除最后一行“TEXT”的所有行。
<div id="content">
<div class="date">2013-02-11 16:19:57</div>
<h2 class="storytitle"><a href="p.php?slug=SOMESLUG">PRPHAHAHAH</a></h2>
<!-- TAGS -->
<div class="tags"><a href="/tag/">slug1</a> <a href="/tag/">slug2</a> <a href="/tag/">slug3</a> </div>TEXT<br />
TEXT<br />
TEXT<br />
TEXT<br />
TEXT<br />
<br />
<pre><code>1
2
3
4
5
</code></pre><br />
<br />
TEXT
<p id="comments" class="separator-story">
<!-- <div class="comments"></a href="/post/Somepost" -->
</p>
</div>
我想在字符串中唯一想要的是:
TEXT<br />
TEXT<br />
TEXT<br />
TEXT<br />
TEXT<br />
<br />
<pre><code>1
2
3
4
5
</code></pre><br />
<br />
TEXT
注意:
答案 0 :(得分:1)
只需找到第一个出现次数和最后出现次数,然后使用它们来构建字符串:
$input = (your input string);
$search = 'TEXT';
$first = strpos($input, $search);
$last = strrpos($input, $search);
$final = substr($input, $first, strlen($input) - $first - $last);
答案 1 :(得分:1)
你走了!
$test= <<<EOM
<div id="content">
<div class="date">2013-02-11 16:19:57</div>
<h2 class="storytitle"><a href="p.php?slug=SOMESLUG">PRPHAHAHAH</a></h2>
<!-- TAGS -->
<div class="tags"><a href="/tag/">slug1</a> <a href="/tag/">slug2</a> <a href="/tag/">slug3</a> </div>TEXT<br />
TEXT<br />
TEXT<br />
TEXT<br />
TEXT<br />
<br />
<pre><code>1
2
3
4
5
</code></pre><br />
<br />
TEXT
<p id="comments" class="separator-story">
<!-- <div class="comments"></a href="/post/Somepost" -->
</p>
</div>
EOM;
$tok = strtok($test, "\n");
$found_start = false;
$found_middle = false;
$found_end = false;
$string_start = "";
$string_middle = "";
$string_end = "";
while ($tok !== false) {
if ( strpos(str_replace(" ", "", $tok), "TEXT" ) === 0) {
if(!$found_middle){
//middle not found yet, so still looking for start
$string_start = $string_start . $tok;
$found_start = true;
} else {
//middle found and this token starts with the key, so it is the end
$string_end = $tok;
$found_end = true;
}
} else if($found_start) {
$string_middle = $string_middle . $tok;
$found_middle = true;
}
if(!$found_end){
$tok = strtok("\n");
} else {
$tok = false;
}
}
echo $string_start . $string_middle . $string_end;