【问题标题】:substring in php whether words is first or last in stringphp中的子字符串,无论单词是字符串中的第一个还是最后一个
【发布时间】:2016-02-04 08:28:01
【问题描述】:

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

“奥尔堡”。

【问题讨论】:

  • 为什么不使用替换字符串?

标签: php substr strpos


【解决方案1】:

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

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

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

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

str_replace()
str_ireplace() // case insensitive

【讨论】:

  • 谢谢!这工作$array = array("studiepakke - ", " - studiepakke", " - standard");$id_name = str_replace($chars, $replace, trim(strtolower(str_ireplace($array, "", $decoded_name))));
【解决方案2】:

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

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.

【讨论】:

    最近更新 更多