开发者

Searching for a string within a string with php?

I am in a bit of a dilemma and can't seem to work out why the following code is not functioning as it should.

function find($haystack, $needles) {
    $needle = array_map('tri开发者_开发问答m', explode(",", $needles));
    foreach ($needle as $key => $value) {
        if (strpos($haystack, $value) !== false) {
            return true;
        }
    }
    return false;
}

I am using the following code as a method to determine what elements should be shown on certain pages or to add classes to certain elements. For example I would use

<?php if (find($section, "home")) { ?> class="current"<?php } ?>

to add the class current if $section = "home". I can also use this function to show certain elements on multiple pages for example

<?php if (find($section, "about, media")) { ?>

and the same if I want to show elements on all pages but not on a selection

<?php if (!find($section, "contact")) { ?>

and lastly it can be used on multiple variables for example.

<?php if (find($page, "news") || find($section, "news")) { ?>

It's when I use the function to try to create a more complex if statement to remove elements from a selection of pages that it seems to fail, in this example the variables and if statement look like this if you on the news section page or the news post page:

<?php if (!find($page, "news") || !find($section, "news")) { ?>

$page = "news" and $section = "media news section"

$page = "post" and $section = "media news post dynamic"

I can't work out why it's not returning false for these specific statements. Any help would be grateful or a better direction/method is welcome. Many thanks


It returns false for the first set of variables, and true for the second set (because $page does not contain 'news'). The code works as expected.

If you want it to return false in both cases, change the OR (||) to AND (&&), so that both conditions must be true (the word news must not be found in either).

if (!find($page, "news") && !find($section, "news")) {
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜