I would like to know how to know how to split the string by | and - and and display the values in php
I have string which i need to split by |and then - and display the value in 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
CodePudding user response:
There are a few things wrong with your code
- All variables must start with a $
$meal = explode('-', $string, 2);
you use $string again instead of $item- With PHP you've to concatenation strings with a
.
not with a - At the end of each line you've to place a ;
If you fix al those problems you get something like:
<?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 />";
}
?>