Forum Moderators: coopster

Message Too Old, No Replies

PHP sscanf?

         

vygbuyhnmj

9:02 pm on Nov 15, 2008 (gmt 0)

10+ Year Member



I want to grab the number 232 out of the following string: "books¦6¦43¦books¦5¦232¦books¦6¦43"

One problem I run into, is that the string will sometimes start with "books¦5¦" and sometimes it will start with something else.

--------- here is what I have done so far --------

I have a string that can look like "books¦6¦43¦books¦5¦232¦books¦6¦43" as well as "books¦5¦232¦books¦6¦43" and "books¦5¦232" and "books¦5¦232¦books¦6¦43"

I am trying to grab the number that appears after "books¦5¦"

The code below works for the string below, however, it only works when the string starts with "books¦5¦"

So when I use:

$string = "books¦6¦43¦books¦5¦232¦books¦6¦43";

It does not work.

$string = "books¦5¦232¦books¦6¦43";
$str_array = sscanf($string, "books¦5¦%d");
$qty = $str_array[0];
echo $qty;

I believe I need to add the regex value before "books¦5¦" so it says to find it in any starting point of the string.

Basically, the end result should be the number that appears after "books¦5¦" (note, this will only appear once in the string).

eeek

12:31 am on Nov 16, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



$r=explode('¦','books¦6¦43¦books¦5¦232¦books¦6¦43');

echo $r[6];

vygbuyhnmj

3:28 am on Nov 16, 2008 (gmt 0)

10+ Year Member



Here's the solution:

$string = "books¦6¦43¦books¦5¦232¦books¦6¦43";
$regex = "/books\¦5\¦(.+?)\¦/";
preg_match($regex, $string , $match);
$current_qty = $match[1];

vincevincevince

3:30 am on Nov 16, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



echo preg_replace("/^.*books\¦5\¦([0-9]+).*$/ism","$1",$string);

vygbuyhnmj - nice expression!