this is my string
$string = "<table><tr><td><a href="https://rads.stackoverflow.com/amzn/click/com/B01IG6C0D4" rel="nofollow noreferrer" target="_blank"><img src="https://images-na.ssl-images-amazon.com/images/I/41ltpJWi8jL._SL160_.jpg" alt="Product Image" style='border:0'/></a></td><td><tr><td>List Price <strike>$17.99</strike></td></tr><tr><td><b>Deal Price: $11.04</b></td></tr><tr><td>You Save: $6.95 (39%)</td></tr><tr><td>Save on the AmazonBasics Foldable Laundry Hamper</td></tr><tr><td>Expires Apr 28, 2017</td></tr></td></tr>";
please help me to extract the 39% (it ca be changed) from this string using regular expression in PHP. I am weak in the regular expression.
Thanks in advance
Using the following regex (one or more digits followed by a % sign) I am able to get the match:
(\d+)\%
Example - https://regex101.com/r/a36Zdl/1
Use the preg_match()
function to match the pattern \\d{1,}\\s*%
means one or more digits (0-9) followed by space or not and finally followed by %
signal.
preg_match()
return if the pattern was matched or not, in case of positive the string (captured) will be store in the third argument ( $m
).
$string = '<table><tr><td><a href="http://rads.stackoverflow.com/amzn/click/B01IG6C0D4" target="_blank"><img src="https://images-na.ssl-images-amazon.com/images/I/41ltpJWi8jL._SL160_.jpg" alt="Product Image" style=border:0/></a></td><td><tr><td>List Price <strike>$17.99</strike></td></tr><tr><td><b>Deal Price: $11.04</b></td></tr><tr><td>You Save: $6.95 (**39%**)</td></tr><tr><td>Save on the AmazonBasics Foldable Laundry Hamper</td></tr><tr><td>Expires Apr 28, 2017</td></tr></td></tr>';
preg_match('/\d{1,}\s*%/', $string, $m);
To capture a number with a fraction this regex (\\d{1,}|\\d{1,}\\.\\d{1,})\\s*%
sounds better
$string = 'asdasd 36.45%';
echo preg_match('/(\d{1,}|\d{1,}\.\d{1,})\s*%/', $string, $m);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.