我应该使用什么函数来搜索段落中的字符串,然后删除包含该字符串后的所有内容?
所以,如果我有一个段落 “玛丽有一只小羊羔和狼吃了它们。然后嫁给了沃尔玛以获得更多的羊羔。”
我使用了一个函数来搜索“lamb”,包括lamb之后的东西,应该删除它之后的东西。所以生成的文本应该是“Marry有点”
答案 0 :(得分:7)
对于这个简单的任务strstr()
会起作用;从PHP 5.3开始,如果将最后一个参数设置为true。
print strstr($text, "lamb", TRUE);
这只返回lamb
之前的部分。
答案 1 :(得分:2)
您可以使用preg_replace()
:
$str = "Marry had a little lamb and the wolf ate them all. Then marry went to Walmart for more lambs.";
$tstr = preg_replace("/lamb(.*)/", "", $str);
答案 2 :(得分:2)
一个快速简单的解决方案是根据第一次出现来拆分字符串,并返回结果数组的第一个索引:
$string = "Marry had a little lamb and the wolf ate them all.";
echo array_shift( explode( "lamb", $string, 2 ) ); // Marry had a little
如果您使用的是现代版本的PHP,@mario's answer是最优雅的。
答案 3 :(得分:2)
未经测试,但应该有效。
$subject = 'Marry had a little lamb and the wolf ate them all. Then marry went to Walmart for more lambs.';
$chopped = substr ($subject, 0, stripos ($subject, 'lamb'));
答案 4 :(得分:1)
我认为这会做你想要的。
<?php
$text = "Marry had a little lamb and the wolf ate them all. Then marry went to Walmart for more lambs.";
$word = 'lamb';
// replace a matching regular expression with '' (an empty string)
$newtext = preg_replace("/\b$word\b.*/", '', $text);
echo $newtext, "\n"; // Marry had a little
我已更新之前的建议(仅"/$word.*/"
),因此它应仅匹配整个单词。
答案 5 :(得分:0)
$poem = "Mary had a little lamb and the wolf ate them all. Then Mary went to Walmart for more lambs.";
$nice_poem = strstr($poem, 'lamb', true); // As of PHP 5.3.0
echo $nice_poem; // prints name although it will keep the lamb to
但是这应该让你接近你需要的东西。
答案 6 :(得分:0)