Preg Replace Issue is stripping numbers/character length? - php

Consider the following example....
The issue is with the preg_replace which is used to replace the variables total_balance_overriden and total_balance.
$text = 'this: {{total_balance_overridden}} - that: {{total_balance}}';
$total = '$517.50';
$overiddentotal = '$390.00';
$text = preg_replace('/{{total_balance_overridden}}/', $overiddentotal, $text);
$text = preg_replace('/{{total_balance}}/', $total, $text);
echo $total;
echo $overiddentotal;
echo $text;
This gives me...
$517.50
$390.00
this: 0.00 - that: 7.50
It appears that the $total and $overiddentotal vars have the correct output, but when they have been replaced using the preg_replace, their length has been stripped, and the currency sign and first two numbers are missing. Any ideas why?
Note: If i replace the dollar sign with a pound sign it works! I get...
this: £390.00 - that: £517.50
So is the dollar sign and 2 numbers some sort of special character or var thats getting stripped?

Dollar signs are special characters in replacement strings, they normally refer to captured substrings from the match. If you want a literal dollar sign, you have to escape it:
$total = '\$517.50';
$overiddentotal = '\$390.00';
Note also, in this case, there's no need for regex at all. Just use str_replace() and you won't have this issue.

Related

Avoid backreference replacement in php's preg_replace

Consider the below use of preg_replace
$str='{{description}}';
$repValue='$0.0 $00.00 $000.000 $1.1 $11.11 $111.111';
$field = 'description';
$pattern = '/{{'.$field.'}}/';
$str =preg_replace($pattern, $repValue, $str );
echo $str;
// Expected output: $0.0 $00.00 $000.000 $1.1 $11.11 $111.11
// Actual output: {{description}}.0 {{description}}.00 {{description}}0.000 .1 .11 1.111
Here is a phpFiddle showing the issue
It's clear to me that the actual output is not as expected because preg_replace is viewing $0, $0, $0, $1, $11, and $11 as back references for matched groups replacing $0 with the full match and $1 and $11 with an empty string since there are no capture groups 1 or 11.
How can I prevent preg_replace from treating prices in my replacement value as back references and attempting to fill them?
Note that $repValue is dynamic and it's content will not be know before the operation.
Escape the dollar character before using a character translation (strtr):
$repValue = strtr('$0.0 $00.00 $000.000 $1.1 $11.11 $111.111', ['$'=>'\$']);
For more complicated cases (with dollars and escaped dollars) you can do this kind of substitution (totally waterproof this time):
$str = strtr($str, ['%'=>'%%', '$'=>'$%', '\\'=>'\\%']);
$repValue = strtr($repValue, ['%'=>'%%', '$'=>'$%', '\\'=>'\\%']);
$pattern = '/{{' . strtr($field, ['%'=>'%%', '$'=>'$%', '\\'=>'\\%']) . '}}/';
$str = preg_replace($pattern, $repValue, $str );
echo strtr($str, ['%%'=>'%', '$%'=>'$', '\\%'=>'\\']);
Note: if $field contains only a literal string (not a subpattern), you don't need to use preg_replace. You can use str_replace instead and in this case you don't have to substitute anything.

Remove empty space and plus sign from the beginning of a string

I have a string that begins with an empty space and a + sign :
$s = ' +This is a string[...]';
I can't figure out how to remove the first + sign using PHP. I've tried ltrim, preg_replace with several patterns and with trying to escape the + sign, I've also tried substr and str_replace. None of them is removing the plus sign at the beginning of the string. Either it doesn't replace it or it remplace/remove the totality of the string. Any help will be highly appreciated!
Edit : After further investigation, it seems that it's not really a plus sign, it looks 100% like a + sign but I think it's not. Any ideas for how to decode/convert it?
Edit 2 : There's one white space before the + sign. I'm using get_the_excerpt Wordpress function to get the string.
Edit 3 : After successfully removing the empty space and the + with substr($s, 2);, Here's what I get now :
$s == '#43;This is a string[...]'
Wiki : I had to remove 6 characters, I've tried substr($s, 6); and it's working well now. Thanks for your help guys.
ltrim has second parameter
$s = ltrim($s,'+');
edit:
if it is not working it means that there is sth else at the beginning of that string, eg. white spaces. You can check it by using var_dump($s); which shows you exactly what you have there.
You can use explode like this:
$result = explode('+', $s)[0];
What this function actually does is, it removes the delimeter you specify as a first argument and breaks the string into smaller strings whenever that delimeter is found and places those strings in an array.
It's mostly used with multiple ocurrences of a certain delimeter but it will work in your case too.
For example:
$string = "This,is,a,string";
$results = explode(',', $string);
var_dump($results); //prints ['This', 'is', 'a', 'string' ]
So in your case since the plus sign appears ony once the result is in the zero index of the returned array (that contains only one element, your string obviously)
Here's a couple of different ways I can think of
str_replace
$string = str_replace('+', '', $string);
preg_replace
$string = preg_replace('/^\+/', '', $string);
ltrim
$string = ltrim($string, '+');
substr
$string = substr($string, 1);
try this
<?php
$s = '+This is a string';
echo ltrim($s,'+');
?>
You can use ltrim() or substr().
For example :
$output = ltrim($string, '+');
or you can use
$output = substr($string, 1);
You can remove multiple characters with trim. Perhaps you were not re-assigning the outcome of your trim function.
<?php
$s = ' +This is a string[...]';
$s = ltrim($s, '+ ');
print $s;
Outputs:
This is a string[...]
ltrim in the above example removes all spaces and addition characters from the left hand side of the original string.

Getting number inside quotes

I have a string that has a number inside exactly one pair of quotes. How can I get this number using php?
I have tried iterating over the string and or using str_split but I'm not sure how to limit it to what is inside the quotation marks. The fact that the number can be any length makes it even harder.
EDIT: Here is an example
Hello this is my "100"th string!,
I would need to return 100;
echo intval('123string');
results in 123
preg_match() is a way to get the number from string. Example:
$str = 'Hello this is my "100"th string!,';
preg_match('/\d+/', $str, $match);
echo $match[0];
Demo
use preg_replace:
echo preg_replace("~[^\d+]~", '', 'Hello this is my "100"th string!,');
trim the quotes from around the string, and php will immediately see the number inside.
$str = "'1234'";
$num = trim($str, "'\"");
echo $num + 1;
// => 1235
or if you have text as well a string, replace all non-digits with spaces, then have
php automatically parse the string when it is used in an arithmetic expression.
$num = preg_replace('/\D/', ' ', $string) + 0;

PHP preg_replace replacing numbers along with special chars

I have the following PHP code to remove special characters from a variable;
<?php
$name = "my%^$##name8";
$patterns = array( '/\s+/' => '_', '/&/' => 'and', '/[^[:alpha:]]+/' => '_');
$name2 = preg_replace(array_keys($patterns), array_values($patterns), trim($name));
echo $name2;
?>
But, along with special chars, numbers also are getting replaced with underscores_. I want to include numbers in the result. How can I fix this?
Your third pattern, /[^[:alpha:]]+/ is replacing everything that's not a letter with an underscore. So add numbers to it, like /[^[:alpha:]0-9]+/
Replace '/[^[:alpha:]]+/' with '/[^[:alpha:][:digit:]]+/'. The original is replacing anything that's not an alphabetic character. Adding [:digit:] means it will replace anything that's not a letter or a number, so your numbers will be preserved as well.

preg_replace - strip unwanted characters from string to return numeric value

I hate regular expressions and I was hoping someone could help with a regualar expression to be used with preg_replace.
I want to strip unwanted characers from a string to return just a numeric value using preg_replace.
The string format could be as follows:
SOME TEXT £100
£100 SOME TEXT
SOME TEXT 100 SOME TEXT
Many thanks
$NumericVal = preg_replace("/[^0-9]/","",$TextVariable);
the ^ inside the [ ] means anything except the following
Edit
removed superfluous +
$l = preg_replace("/[^A-Z0-9a-z\w ]/u", '', $l);
Works witch UTF-8, allow only A-Z a-z 0-9 łwóc... etc
preg_replace('/[^0-9]/','',$text);
Try this:
preg_replace("/\D+/", "", "SOME TEXT £100")
You can also use preg_match to get the first number:
preg_match("/\d+/", "SOME TEXT £100", $matches);
$number = $matches[0];

Categories