我想知道如何通过|和-和来分割字符串并在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
您的代码有一些错误
- 所有变量都必须以$
$meal = explode('-', $string, 2);
您再次使用$string而不是$item- 使用PHP时,必须将字符串与
.
连接起来,而不是与+
连接起来 - 在每一行的末尾,你必须放置一个
如果你解决了所有这些问题,你会得到这样的东西:
<?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 />";
}
?>