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

Link to comment
Share on other sites

<?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);

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.