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"] 可以看起来像 "aalborg - studiepakke",但也可以是 "studiepakke - aalborg"

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

"aalborg".

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

$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.