查找字符串的一部分并输出整个字符串

Find part of a string and output the whole string

我想找到字符串的一部分,如果 true 我想输出它找到的整个字符串。

下面是一个例子:

$Towns = "Eccleston, Aberdeen, Glasgow";
$Find = "Eccle";

if(strstr($Find, $Towns)){
    echo outputWholeString($Find, $Towns); // Result: Eccleston.
}

如果有人也能阐明如何做到这一点,请记住它不会是静态值; $Towns$Find 变量将在我的实时脚本中动态分配。

你快到了...

这可能是您要查找的内容:

<?php
$Towns = "Eccleston, Aberdeen, Glasgow";
$Find = "Eccle";

if(stripos($Towns, $Find)) {
    echo $Towns;
}

输出是:Eccleston, Aberdeen, Glasgow,我称之为 "the whole string"。


但是,如果您只想输出 "the whole string" 的 部分 部分匹配的部分,请查看该示例:

<?php
$Towns = "Eccleston, Aberdeen, Glasgow";
$Find = "Eccle";

foreach (explode(',', $Towns) as $Town) {
    if(stripos($Town, $Find)) {
        echo trim($Town);
    }
}

输出显然是:Eccleston...

两条一般性评论:

  1. strpos() / stripos() 函数更适合这里,因为它们 return 只是一个位置而不是整个匹配的字符串,这对于给定的目的。

  2. 使用 stripos() 而不是 strpos() 执行不区分大小写的搜索,这可能对任务有意义...

使用 preg_match(),可以搜索 Eccle 和 return Eccleston 词。

我在下面的代码和 demo 代码中使用了 Pearl 兼容正则表达式 (PCRE) '#\w*' . $Find . '\w*#'

# 个字符是 PCRE 分隔符。搜索的模式在这些定界符内。有些人更喜欢 / 作为分隔符。
\w表示个字符。
* 表示前一个字符重复 0 次或多次。
因此,#\w*Eccle\w*# PCRE 搜索包含 Eccle 并被一个或多个 word 个字符包围的字符串 (letters)

<?php
$Towns = "Eccleston, Aberdeen, Glasgow";
$Find = "Eccle";

if (preg_match('#\w*' . $Find . '\w*#', $Towns, $matches)) {
    print_r($matches[0]);
}
?>

运行代码:http://sandbox.onlinephpfunctions.com/code/4e4026cbbd93deaf8fef0365a7bc6cf6eacc2014

注意:'#\w*' . $Find . '\w*#'"#\w*$Find\w*#" 相同(注意周围的单引号或双引号)。参见 this

您必须使用 strpos() 在另一个字符串中搜索一个字符串:

if( strpos($Towns, $Find) === false ) {
    echo $Towns;
}

请注意,您必须使用“===”才能知道 strpos() 是否返回 false 或 0。

使用explode()strpos()作为

$Towns = "Eccleston, Aberdeen, Glasgow";
$data=explode(",",$Towns);// 
$Find = "Eccle";
foreach ($data as $town)
if (strpos($town, $Find) !== false) {
    echo $town;
}

DEMO

使用preg_match函数的解决方案:

$Towns = "Eccleston, Aberdeen, Glasgow";
$Find = "Eccle";

preg_match("/\b\w*?$Find\w*?\b/", $Towns, $match);
$result = (!empty($match))? $match[0] : "";

print_r($result);   // "Eccleston"

假设 $Towns 始终由“,”分隔,那么您可以这样做

$Towns = "Eccleston, Aberdeen, Glasgow";
$Find = "Eccle";    
$TownsArray = explode(", ", $Towns);

    foreach($TownsArray as $Town)
    {
       if(stristr($Find, $Town))
       { 
          echo $Town; break;
       }
    }

上面的代码一旦找到针就会输出Town并退出foreach循环。您可以删除 "break;" 以继续让脚本 运行 查看它是否找到更多结果。