How to extract a string within another ?

Hi all,

I would like to extract the amount "62" in the following string. It corresponds to the total amount.

s:14:\"PaymethodTotal\";s:1:\"0\";s:5:\"Total\";d:62;s:6:\"Remark\";s:0:\"\";

How can I do that ?

TIA
LVL 1
Richard Coffree-commerce Product ManagerAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
hernst42Connect With a Mentor Commented:
you can try using a regular expression like this:

$str = 's:14:\"PaymethodTotal\";s:1:\"0\";s:5:\"Total\";d:62;s:6:\"Remark\";s:0:\"\"';
if (preg_match('/Total.?";d:(\d+(\.\d+)?)/', $str, $m)) {
    echo $m[1];
}

0
 
ldbkuttyCommented:
You can use explode() function to extract the string:

<?php
     $myString = 's:14:\"PaymethodTotal\";s:1:\"0\";s:5:\"Total\";d:62;s:6:\"Remark\";s:0:\"\"';
     $getSubString = explode(';', $myString);
     echo $getSubString[3];   // Displays d:62
     $getNumber = explode(':', $getSubString[3]);
     echo "<br> " . $getNumber[1]; // Diplays 62
?>

PS: There are numerous other ways like strpos(), strrchr(). It depends on how your string is organized.
0
 
Richard Coffree-commerce Product ManagerAuthor Commented:
Is there a way to define a pattern,  e.g. s:5:\"Total\";d:$$;s:6:\"Remark\" where $$ represents the value we want to retrieve ?
0
Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

 
RoonaanCommented:
The looks a awfull lot like a string being serialized with serialize.

Possibly you can use:

$array = unserialize('....text u showed....');

and then $array['Total'] holds the value 62.

Regards

-r-
0
 
eeBlueShadowCommented:
try:

$str = 's:14:\"PaymethodTotal\";s:1:\"0\";s:5:\"Total\";d:62;s:6:\"Remark\";s:0:\"\"';
$pattern = ';d:(\d+);';

if (preg_match_all($pattern, $str, $m, PREG_SET_ORDER)) {
    print_r($m);
}

after the preg_match_all, $m[1] should have a list of all the 'd' values
0
 
suresh_aspCommented:
Try this,


$string = "s:14:\"PaymethodTotal\";s:1:\"0\";s:5:\"Total\";d:62;s:6:\"Remark\";s:0:\"\";";
$changed = preg_match_all("/d:(\d+)/",$string,$res);
echo $res[1][0];
0
 
Richard Coffree-commerce Product ManagerAuthor Commented:
Thanks for all your answers.
0
All Courses

From novice to tech pro — start learning today.