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

php中的子字符串,无论单词是字符串中的第一个还是最后一个,php,substr,strpos,Php,Substr,Strpos,我使用这段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

我使用这段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”是在字符串的开头还是结尾并不重要。我的最终结果永远是


“奥尔堡”。

如果我没弄错,你可能想在破折号所在的位置拆分字符串。 为此,请使用

$substrings = explode(" - ", $string);
这将为您提供一个子字符串数组,然后您可以检查哪个子字符串是搜索到的

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

str_replace()
str_ireplace() // case insensitive

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

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


为什么不使用替换字符串?谢谢!这项工作
$array=array(“studiepakke-”、“-studiepakke-”、“-standard”)
$id\u name=str\u replace($chars,$replace,trim(strtolower(str\u ireplace($array,“,$decoded\u name)))
if(preg_match("/(^studiepakke|studiepakke$)/i", $campaign["campaign_name"])) //studiepakke is exacly at begin or ending of the string.