如何在php中拆分字符串和迭代



我想知道如何通过|和-和来分割字符串并在php 中显示值

我有一个字符串,我需要用|和-来分割,并在php中显示值

<?php
$string = 'city-3|country-4';
$str1 = explode('|', $string, 2);
foreach ($str1 as $item) {
 $meal = explode('-', $string, 2);
      if (meal[0]=="city")
        {
            echo "city duration    " + meal[1]
        }
        else if (meal[0]=="country")
        {
            echo "country duration   " + meal[1]
        }
}
?>
ExpectedOutput
city duration 3
country duration 4

您的代码有一些错误

  1. 所有变量都必须以$
  2. $meal = explode('-', $string, 2);您再次使用$string而不是$item
  3. 使用PHP时,必须将字符串与.连接起来,而不是与+连接起来
  4. 在每一行的末尾,你必须放置一个

如果你解决了所有这些问题,你会得到这样的东西:

<?php
$string = "city-3|country-4";
$str1 = explode('|', $string, );
foreach ($str1 as $item) {
        $meal = explode('-', $item, 2);
        if ($meal[0]=="city")
        {
            echo "city duration    " . $meal[1];
        }
        else if ($meal[0]=="country")
        {
            echo "country duration   " . $meal[1];
        }
        echo "<br />";
}
?>

最新更新