Jump to content

[SOLVED] return part of a string


n8w

Recommended Posts

Well if you're going to need to search the same string multiple times, i'd build an array:

 

<?php
$id=339;
$str="338:1, 339:3 ,340:15";

$pieces = explode(",",$str);
$array = array();
foreach($pieces as $piece){
    $piece = trim($piece);
    list($key,$value) = explode(":",$piece);
    $array[$key] = $value;
}

//can then access based on id
if(isset($array[$id]){
    echo $array[$id];
}else{
    echo "That id doesn't exist!";
}
?>

 

If it's just the once, a regex would be neater.

 

Edit: e.g:

 

<?php
$id=359;
$str="338:1, 339:3 ,340:15";
preg_match("|$id:([0-9]+)|",$str,$matches);
if(count($matches) > 0){
    echo $matches[1];
}else{
    echo "That ID doesn't exist!";
}
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.