Jump to content

Get value from text string


johnsmith153

Recommended Posts

I want to get the price from a text string

 

$string = "sssssssssss ggggggggg $44 test here";

 

So to return 44 for above.

 

The only thing is the currency could change to another value (e.g. a pound sign (which this site won't let me post)).

 

I can find if the value exists etc. but the difficulty is in getting the value next to the symbol (e.g. 44 next to $).

Link to comment
https://forums.phpfreaks.com/topic/266882-get-value-from-text-string/
Share on other sites

Is the currency symbol the only thing that would be different? For example, could the value be a decimal such as $44.32? What about grouping, e.g. 1,234.56? Will the value always have a space before and after it? Can a space be between the currency symbol and the first digit, e.g. $ 12? All of these are very important considerations when developing the right solution. As for the currency symbol you would have to define a list of the currency symbols that would be used. But, I'm not going to take time to write anything without answers to the above.

No, just simple.

 

So grab everything after a defined value and ignore if spaces in between. Also grab the first occurence only

 

function get_price ($search_value, $string) {

}

echo get_price ("$", "sssssssssss ggggggggg $44 . 99 $$$ dffg test here"); // returns 44

<?php
$currency = '$';
$string = 'This item costs $29.97. You may pay cash or credit.';

$find = '/\\' . $currency . '[0-9]*[.]?[0-9]{0,2}/';

preg_match($find, $string, $matches);

echo 'Searching for "' . $find . '" in "' . $string . '" <br />';

print_r($matches);

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.