首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >php:通过子子串从字符串中提取子串

php:通过子子串从字符串中提取子串
EN

Stack Overflow用户
提问于 2013-02-01 22:12:06
回答 3查看 436关注 0票数 1

我们有一些字符串$text="Here are some text. The word is inside of the second sentence.";$word="word";

How to get $sentence="The word is inside of the second sentence"; -包含" ".$word." "的第一句话

当然,也应该做一些假设。其中之一是所有句子都以".\r\n""!\r\n"". ""! "结尾。

附言:我们确信strpos($text," ".$word." ")!==false

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-02-01 22:26:56

您的文本:

代码语言:javascript
运行
复制
$txt = "word word word different. different word word word. word word word ending. word word word";

我的话是“不同的”:

代码语言:javascript
运行
复制
$word = "different";

让我们做一个preg匹配:

代码语言:javascript
运行
复制
$c=preg_match("/(\.|^)([^\.]*?".$word."[^\.]*(\.|$))/",$txt,$match);

如果成功,则显示包含该句子的第二组:

代码语言:javascript
运行
复制
if($c!==false and count($match) > 0 )
    echo( $match[2]) ;

这将返回第一个实例。如果您想要全部使用preg_match_all。

票数 1
EN

Stack Overflow用户

发布于 2013-02-01 22:26:45

你可以使用类似这样的东西:

代码语言:javascript
运行
复制
<?php

$text="Here are some text. The word is inside of the second sentence. And the word is also in this sentence!";
$word = 'word';


function getSentenceByWord($text, $word) {

    $sentences = preg_split('/(\.|\?|\!)(\s)/',$text);
    $matches = array();
    foreach($sentences as $sentence) {

        if (strpos($sentence,$word) !== false) {
            $matches[] = $sentence;
        }

    }

    return $matches;
}

print_r(getSentenceByWord($text, $word));
?>

返回:

代码语言:javascript
运行
复制
Array
(
    [0] => The word is inside of the second sentence
    [1] => And the word is also in this sentence!
)
票数 1
EN

Stack Overflow用户

发布于 2013-02-01 22:38:14

没有正则表达式,只有一个分隔符".":

代码语言:javascript
运行
复制
<?php
$text="Sentence one. Sentence two. Sentence three. Sentence four.";

$word_pos = strpos($text, "Sentence");
$start = strrpos(substr($text, 0, $word_pos), ".");
$end = strpos(substr($text, $word_pos), ".");

$start = $start ? $start + 2 : 0;
$end = $end + $word_pos + 1 - $start;

$sentence = substr($text, $start, $end);

echo $sentence;
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14648174

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档