I have a string that could be something like "$2.99" or could be "$1.99 - $20.99" with multiple prices in the string.
I would like to wrap the cents in a superscript tag.
So far I have been trying:
$price = [could be "$x.xx" or could be "$x.xx - $xx.xx"];
$pattern = '/(\$[\d,]+\.)(\d+)([\s\-]*\$[\d,]*\.*)(\d*)(.*)$/';
$formattedPrice = preg_replace($pattern, '$1<sup>$2</sup>$3<sup>$4</sup>$5', $price);
But that only matches "$x.xx - $xx.xx" not just "$x.xx"
Is there a good way to just find all instances of a period and wrap the next two characters?
Thanks.
Try this:
$pattern = '/\.([\d]{2})/';
This pattern will match any two digits that are directly following a period.
preg_replace($pattern, '.<sup>$1</sup>', '$2.99');
preg_replace($pattern, '.<sup>$1</sup>', '$1.99 - $20.00');
Output:
string(16) "$2.<sup>99</sup>"
string(36) "$1.<sup>99</sup> - $20.<sup>00</sup>"
If you wanted to guard against not selecting any random two digits following a period but specifically in a dollar amount, you can add to it to ensure you're correctly targetting the right substrings with this pattern:
$pattern = '/\$\d\.([\d]{2})/';
if you want to wrap the cents then you could use:
(\$\d+\.)(\d+)
Working demo
Related
Consider the following string:
' "z":"100", "a":"+0.5", "b":"-0.578", "c":"-.5", "d":".55", "e":"-5",
"f":"01234", "g":"0.999", "i":"153.35" '
I'm trying to convert every number in this string while retaining the negative sign, except the ones starting with a 0 that arent float. In other words, I'm trying to convert to
' "z":100, "a":0.5, "b":-0.578, "c":-.5, "d":.55, "e":-5, "f":"01234", "g":0.999, "i":153.35 '
This is what I have so far
preg_replace('/((?:\:")(?:[\+])?[\-]?([0-9\.]+?)[0-9]+(?:"))/', '$1', $string);
Which isn't enough.. The hard part is to keep the " around 01234 while removing them for the other numbers..
Basically I'd like to ignore
(\:"[0][0-9]+")
Regexr link
You can use the regex (:)"(?!0\d+")\+?(-?(?:\d*\.)?\d+)" and replace it with $1$2.
See ideone
$str = '"z":"100", "a":"+0.5", "b":"-0.578", "c":"-.5", "d":".55", "e":"-5", "f":"01234", "g":"0.999", "i":"153.35", "0":"5"';
$pattern = '/(:)"(?!0\d+")\+?(-?(?:\d*\.)?\d+)"/';
print(preg_replace($pattern, '$1$2', $str));
You can use this regex to match all the numbers between quotes:
(?<=")(?!0\d)[+-]?\d*\.?\d+(?=")
EDIT: Sorry misread your question, I updated the regex to match every number but the ones beginning with 0 that aren't floats
I would like to get the second number present in a string.
Maybe you have better ideas than mine.
From this example:
1 PLN = 0.07 Gold
I would like to get only "0.07" from that string.
I obtain it from web scraping so it returns me as a string.
The problem that I have is the following.
The "second number in string" might be with ".", without it, might be composed by only one number ex. "1", or by two "12", might have decimals ex. "1.2", even position may change, because for some currency I will have "1 PLN", "1 USD" for others I will have "1 TW".
So I can't work on position, I can't extract only numbers (I have the "1" at the beginning of the string), I can't extract only INT cause I could have also decimals...
So the only constant of that string - I think (but if you have better ideas pls suggest me) - is that I need the second number I find in the string.
How could I get it?
Sorry If I wasn't enough clear.
Try this:
<?php
$string = '1 PLN = 0.07 Gold';
$pattern = '/\d+\.\d+/';
$matches = array();
$r = preg_match($pattern, $string, $matches);
var_dump($matches); //$matches is array with results
Output:
array(1) {
[0]=>
string(4) "0.07"
}
If its always in this format 1 PLN = 0.07 Gold You can just
$array = explode(" ", $string) with a Space and then get the required number with
$number = $array[3]
Try it out, let me know if it works
You can use a simple regex patter to isolate all numbers, including decimals if any after the equals sign.
The below works if the string will have the same structure, meaning an = a space and then the number that you are after.
= - matches the equals sign
\s - matches the space character immediately after
(\d*\.?\d*) - matches any number of digits followed by an optional period . and then any number of digits
$str = '1 PLN = 0.07 Gold';
preg_match('#=\s(\d*\.?\d*)#',$str,$matches);
print $matches[1];
Will output
0.07
This works regardless of what you have before the = sign.
I'm trying to work out a quick and simple way to remove the first two digits and a decimal
from a string, if that is how it is made up.
I am half way there but need help to finish.
So (first is what I start with, 2nd is the result):
xx.yyy = yyy
aaaaa = aaaaa
test.hello = test.hello
a.test.b.x = a.test.b.x
aa.bb.cc = bb.cc
So it only removes 2 digits and a decimal if it exists like that. If it is three digits and a decimal then it isn't removed.
This is where I am so far:
$string = 'xx.hello';
$pattern = '/(2-digits)./i';
$replacement = ''; // remove if matched
echo preg_replace($pattern, $replacement, $string);
?>
This will do letters, digits, and underscores:
preg_replace('/^\w{2}\./', '', $string);
Without numbers or underscores, both upper and lowercase:
preg_replace('/^[a-zA-Z]{2}\./', '', $string);
Assuming by "digits" you mean actual digits (0-9) and by "decimal" a dot:
$string = preg_replace('/^\d{2}\./','',$string);
Try the following:
$pattern = "~^[0-9A-Za-z]{2}\\.~";
It matches two alphanumerical characters at the beginning of the string, followed by a period (.). Notice that the period has been escaped so the period is interpreted as a literal. (Otherwise, the period matches any single character.)
Using php regexp in a simple way, is it possible to modify a string to add a space after commas and periods that follow words but not after a comma or period that is preceded and followed by a number such as 1,000.00?
String,looks like this with an amount of 1,000.00
Needs to be changed to...
String, looks like this with an amount of 1,000.00
This should allow for multiple instances of course... Here is what I am using now but it is causing numbers to return as 1, 000. 00
$punctuation = ',.;:';
$string = preg_replace('/(['.$punctuation.'])[\s]*/', '\1 ', $string);
You could replace '/(?<!\d),|,(?!\d{3})/' with ', '.
Something like:
$str = preg_replace('/(?<!\d),|,(?!\d{3})/', ', ', $str);
I was searching for this regex.
This post really help me, and I improve solution proposed by Qtax.
Here is mine:
$ponctuations = array(','=>', ','\.'=>'. ',';'=>'; ',':'=>': ');
foreach($ponctuations as $ponctuation => $replace){
$string = preg_replace('/(?<!\d)'.$ponctuation.'(?!\s)|'.$ponctuation.'(?!(\d|\s))/', $replace, $string);
}
With this solution, "sentence like: this" will not be changed to "sentence like: this" (whith 2 blanck spaces)
That's all.
Although this is quite old, I was looking for this same question, and after understanding solutions given I have a different answer.
Instead of checking for character before the comma this regex checks the character after the comma and so it can be limited to alphabetic ones. Also this will not create a string with two spaces after a comma.
$punctuation = ',.;:';
$string = preg_replace("/([$punctuation])([a-z])/i",'\1 \2', $string);
Test script can be checked here.
I have a string Trade Card Catalogue 1988 Edition I wish to remove everything apart from 1988.
I could have an array of all letters and do a str_replace and trim, but I wondered if this was a better solution?
$string = 'Trade Card Catalogue 1988 Edition';
$letters = array('a','b','c'....'x','y','z');
$string = str_to_lower($string);
$string = str_replace($letters, '', $string);
$string = trim($string);
Thanks in advance
Regular expression?
So assuming you want the number (and not the 4th word or something like that):
$str = preg_replace('#\D#', '', $str);
\D means every character that is not a digit. The same as [^0-9].
If there could be more numbers but you only want to get a four digit number (a year), this will also work (but obviously fails if you there are several four digit numbers and you want to get a specific one) :
$str = preg_replace('#.*?(\d{4,4}).*#', '\1', $str);
You can actually just pass the entire set of characters to be trimmed as a parameter to trim:
$string = trim($string, 'abc...zABC...Z ' /* don't forget the space */);