PHP 中的子字符串,无论单词在字符串中是第一个还是最后一个


substring in php whether words is first or last in string

我有这段PHP在字符串中查找活动名称,然后在活动名称出现时使用substr。

 $chars = array("æ", "ø", "å");
 $replace = array("ae", "oe", "aa");
 $dash = strpos(utf8_decode($campaign["campaign_name"]), "Studiepakke");
 $decoded_name = utf8_decode($campaign["campaign_name"]);
 $id_name = str_replace($chars, $replace, trim(strtolower(substr($decoded_name, 0, ($dash-2)))));
 $lpage_pos = strripos($id_name, $_GET["lpage"]);
 $short_name = strtolower(utf8_decode($campaign["adset_name"]));
 $dash_pos = strpos($short_name, " - ");

$campaign["campaign_name"]可以看起来像"奥尔堡-Studiepakke",但也可以是"Studiepakke - Aalborg"

我如何使用 substr 和 strpos,所以"Studiepakke"是在字符串的开头还是结尾并不重要。我的最终结果永远是

"奥尔堡"。

如果我

做对了,你可能想在破折号所在的位置拆分字符串。为此,请使用

$substrings = explode(" - ", $string);

这将为您提供一个子字符串数组,然后您可以检查哪个是搜索的子字符串。

您还可以使用字符串替换将不需要的部分替换为空字符串。

str_replace()
str_ireplace() // case insensitive

对于您所描述的问题,我有一些不同的方法:

if(strpos($campaign["campaign_name"], "studiepakke")) //studiepakke is part of the string.

或:

if(preg_match("/(^studiepakke|studiepakke$)/i", $campaign["campaign_name"])) //studiepakke is exacly at begin or ending of the string.