Jump to content

[SOLVED] return part of a string


n8w

Recommended Posts

I want to dynamically search a string.

So if $id=339;

I would like it to return the number after the ":" which would be "3"

 

What is the best way to do this?

 

 

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

 

Link to comment
Share on other sites

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!";
}
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.