查找数组值是否出现在字符串中。 (有点相反的 in_array ?)

发布于 2024-12-19 10:30:45 字数 668 浏览 1 评论 0原文

在我正在开发的网站上,有一个副标题,只有当主标题中尚未显示信息时才应显示该副标题。主标题是任意字符串,而副标题是通过编程创建的。副标题是根据多维数组的内容生成的(该数组的内容也用于页面的其他部分。)

我使用了 foreach 的 PHP 示例来向下钻取该数组(只是不太了解它是如何工作的),然后尝试 strpos 来查看数组中的值是否在标题字符串中。

不幸的是,它不起作用。我很可能在我认为它应该如何工作方面犯了一个愚蠢的错误。或者,由于数组中的其他值,告诉网站隐藏副标题(“隐藏者”)的变量不断重置为“否”。

foreach ($arr_info as $i1 => $n1) {    
    foreach ($n1 as $i2 => $n2) {     
        foreach ($n2 as $i3 => $n3) {
            $pos = strpos($headline, $n3);
            if ($pos === false) {
                $hider="no";
            } else {
                $hider="yes";
            }
        }
    }

有什么想法吗?非常感谢您的帮助。

On a site I'm working on there's a subheadline that only should be shown if the information isn't already shown in the main headline. The main headline is an arbitrary string, while the subheadline is created programatically. The subheadline is generated from the contents of a multi-dimensional array (the contents of which are also used for other parts of the page.)

I used the PHP example of foreach to drill down through the array (only half-understanding how it was working), and then tried strpos to see if the values in the array were in the headline string.

Unfortunately, it doesn't work. There is a high chance that I made a stupid mistake in how I thought it's supposed to work. Or that the variable that tells the site to hide the subhead ("hider") is constantly reset to "no" as a result of the other values in the array.

foreach ($arr_info as $i1 => $n1) {    
    foreach ($n1 as $i2 => $n2) {     
        foreach ($n2 as $i3 => $n3) {
            $pos = strpos($headline, $n3);
            if ($pos === false) {
                $hider="no";
            } else {
                $hider="yes";
            }
        }
    }

Any ideas? Greatly appreciate the help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

氛圍 2024-12-26 10:30:45

补充一下:

$hider="yes";
break;

希望有帮助

Add this:

$hider="yes";
break;

Hope it helps

绳情 2024-12-26 10:30:45

我认为更干净的方法是根据值构造一个正则表达式,看看它是否与您的字符串匹配:

$values = array();
array_walk_recursive($arr_info, function($k){$GLOBALS['values'][] = preg_quote($k);});
$hider = preg_match('/(' . implode($values, '|') . ')/', $headline) ? 'yes' : 'no';

I think a cleaner approach would be to construct a regex out of the values and see if it matches your string:

$values = array();
array_walk_recursive($arr_info, function($k){$GLOBALS['values'][] = preg_quote($k);});
$hider = preg_match('/(' . implode($values, '|') . ')/', $headline) ? 'yes' : 'no';
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文