Question

Let say I have a huge string where I want to extract e certain value belonging to a name, for example the stockprice of Apple.

Let say say the string look like this (in reality its html but that does not matter here)

$output = "nsdfsdnfsnfdnsdfnueruherdfndsdndnjsdnasdnn Apple dndfjnfjdf647tgtgtgeq";

I want to extract the value 647.

The real string is maybe some hundred thousand characters.

I can reveal the position of Apple by:

$str = "Apple";
$pos = strpos($output, $str);

let say the function returns 87310 which is the indexposition of the first letter in Apple.

Here comes my question? Is there an easy way to extract the value when I know the startposition of Apple? I have looked for such a function but can right now not find it. I could solve this easily by just looping ahead of the name Apple and then extract the relevant characters? But it would at the least save keystrokes to use a function for this instead.

Thanks!!!

Was it helpful?

Solution

To just pull out the stock price, you would want to do something like this:

Search your string for "Apple" and save $position + 5 (length of Apple). Search directly after $position, one character at a time, for the first character that is_numeric and add that to a string, $stock_val. Continue adding all subsequent characters until you find one that !is_numeric. Here is my clunky code:

$position = strpos(strtolower($str), "apple") + strlen("apple");
$temp_str = substr($str, $position);

$stock_val = "";

do {
$char = substr($temp_str, 0, 1);   //Take first char of $temp_str
$temp_str = substr($temp_str, 1);  //Remove that char from $temp_str

    $is_acceptable = (is_numeric($char) || $char == "." || $char == ",");
if($is_acceptable) {            //If the char is_numeric, add it to $stock_val
    $stock_val .= $char;
}
if(!$is_acceptable && $stock_val != "") {
    break;                     //If the char is NOT numeric AND $stock_val
}                              //already has characters, break.
} while(strlen($temp_str) > 0);        //Repeat while there are still characters

OTHER TIPS

you know the start position so calculate the end position by doing strlen($str) then use substr to cut away the unwanted string something like this using substr

$portion = substr(substr($string, 0, -(strlen($string) - $end)), $start);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top