Str replace dont seem to match certain strings - php

I have a script which takes in some user input, cleans it and tries to replace the value in a string. I found that the str replace that I use cant seem to match e.g. 11 +tum. Why is that? Can I fix it some way? Does preg replace manage it, and if so how does that look in preg replace?
Function
The script prepares the user input string for a full text query, all words are mandatory so each space is replaced with space+. But some phrases like 11 tumneed to be searchable and thus put in double quotes. The failing part is that the scirpt cant seem to match some phrases even though echoing the valus before comparison shows they are the same, e.g. 11 tum
Code:
//processedQuery e.g. 'laptop 11 tum'
$processedQuery = str_replace(" "," +",$processedQuery);
echo processedQuery; //parses laptop +11 +tum
foreach($commonQuery as $value){ //$commonQuery = array("11 tum", "13 tum", "15 tum", "17 tum", "asus eee", "asus 1005","asus 1010")
//compile : simulated query format error
$simulatedErrorValue = str_replace(" "," +",$value);
echo simulatedErrorValue; //parses 11 +tum
$processedQuery = str_replace($simulatedErrorValue,'"'.$value.'"',$processedQuery);
}
echo $processedQuery; //parses laptop +11 +tum
//exchange 11 tum for asus eee (the other commonQuery and the last echo of $processedQuery shows the correct laptop +"asus eee"

You are confusing the input to your function. I'm getting the desired result with a small modification:
11 +tum
laptop +"11 tum"
asus +eee
laptop +"11 tum"
Your error is this line:
$commonQuery = array("11 tum, asus eee")
This is an array with just 1 member.
You want to change the array to have 2 members:
$commonQuery = array("11 tum" , "asus eee");
Here is my full code:
<?php
$processedQuery = 'laptop 11 tum';
$processedQuery = str_replace(" "," +",$processedQuery);
$commonQuery = array("11 tum" , "asus eee");
foreach ( $commonQuery as $value ) { //$commonQuery = array("11 tum, asus eee")
//compile : simulated query format error
$simulatedErrorValue = str_replace(" "," +",$value);
echo "$simulatedErrorValue\n"; //parses 11 +tum
$processedQuery = str_replace($simulatedErrorValue,'"'.$value.'"',$processedQuery);
echo "$processedQuery\n";
}
?>

Related

Print number with spaces as thousands place separator [duplicate]

This question already has answers here:
PHP - Correct way to add space between numbers?
(3 answers)
Closed 1 year ago.
I'm trying to reverse a string and add spaces from 3 in 3 characters the code I have right now is this:
$rowPreco = "925000"
$rowPreco = strrev($rowPreco);
$rowPreco = wordwrap($rowPreco , 3 , ' ' , true );
$rowPreco = strrev($rowPreco);
if I take the strrev out it prints how I want ("925 000") but if I have the strrev it will print ("92 500 0").
But I need to use the strrev because if the value is ("1200000") it will print ("120 000 0") instead of ("1 200 000").
Any help would be appreciated.
Thanks!
UPDATE!
When I use the number_format it will ignore a jQuery code that I have.
echo "<script>"
."jQuery(document).ready(function() {"
."var parts = jQuery('.casaPreco').text().split('|');"
."jQuery('.casaPreco2').text(parts[4]);"
."});"
."</script>";
Basically the initial string is something like this: "3880562|1|1|925000|||0|0|0"
I need to grab the 4th number so I'm splitting the string on the "|" and use the array parts[4] but when I use the number_format it will grab the number "3880562"
Please do not invent the wheel:
echo number_format('925000', 0, '.', ' '); // 925 000
echo number_format('1200000', 0, '.', ' '); // 1 200 000
number_format manual.

How to get measument name out of a string in PHP

I have a feed in array form which contains area of construction
$x['AC']="25";
sometime it comes with the measurement value attached in the string itself
$x['AC']="25mt2"; or $x['AC']="25 mt2"; or $x['AC']="25m2";
$x['AC']="25ht2"; or $x['AC']="25 ht2"; or $x['AC']="25h2";
how can I detect this and then clean the value of the array to just number .
and once its detected I have to create a string like
mt2[;;;]25 or ht2[;;;]25
Thanks in advance
I would use a preg to remove other caracters than numbers:
$x['AC'] = preg_replace('/\D+/','',$x['AC']);
But would leave any additional value besides the 25 that you refer, but if 25 is the first number, i would use a preg to get the first numbers in the string:
if(!is_numeric($x['AC'])){
preg_match('/^\d+/',$x['AC'],$nr);
$x['AC'] = $nr[0];
}
To get the inside mt or ht also, i would modify the regex like:
if(!is_numeric($x['AC'])){
preg_match('/^(\d+)\s?(.*)$/',$x['AC'],$nr);
$x['AC'] = $nr[1];
$mtORht = $nr[2];
}
OK, resuming, so m2 is default, and for anything else you wish to create a variable with that value in array:
OK, float values too:
if(!is_numeric($x['AC'])){
preg_match('/^([0-9\.]+)\s?(.*)$/',$x['AC'],$nr); //$x['AC']="25 ht2"
$theValue = $nr[1]; //25
$theMeasurementName = $nr[2]; //ht2
//creating the variable:
if(!stristr($theMeasurementName, 'm')){ // if no "m" is found, the m you wish to omit.
${$theMeasurementName} = $theValue; // $ht2[] = 25
}
}
You can just cast it to an integer and if there is a non numerical value it will get cut off, like this:
$x['AC'] = (int) $x['AC'];
example input/output:
25 -> 25
25mt2 -> 25
25ht2 -> 25
25 mt2 -> 25
25 ht2 -> 25
25m2 -> 25
25h2 -> 25
EDIT:
As per your updated question you can use preg_match() to create your string:
preg_match("/^(\d+)\s*(.*?)$/", $x["AC"], $m);
echo (empty($m[2])?"m2":$m[2]) . "[;;;;]" . $m[1];
$match = array();
preg_match('/^\d+/', $string, $match));
echo $match[0];
Regex:
^ -> begin with
\d+ -> any digit repeated

strpos() doesn't seem to be recognizing my the string I am using

I have the following string:
CAE33D8E804334D5B490EA273F36830A9849ACDF|xx|yy|46|13896|9550
which in the code below corresponds to $track_matches[0][0].
The only constant-length field is the first (CAE33D8E804334D5B490EA273F36830A9849ACDF), which is 40 characters long. I am trying to get the values xx and yy which are an unknown length and value along with the rest of the column.
So I am trying something like this:
$seperator= '|';
$end_seed= strpos($track_matches[0][0], $seperator, 41 );
$seeders[$i] = substr($track_matches[0][0], 41, $end_seed - 41);
$end_leech= strpos($track_matches[0][0], $seperator, $end_seed +1 );
echo "end_seed" . $end_seed . " end_leach: " . $end_leech;
$leechers[$i] = substr($track_matches[0][0], $end_seed +1, $end_leech - $end_seed - 1);
The problem I am getting is the line $end_leech= doesn't seem to work properly (and doesn't recognize the $seperator) and retuns the entire line ($track_matches[0][0]) as it's value when echo'd while $end_seed returns the proper value. ... so what's going on why is this happening? howw do i fix it?
try:
$temp = explode("|", $track_matches[0][0]);
That will return an array and you can then reference the vars as $temp[1] (xx) and $temp[2] (yy)
try :
$myString="CAE33D8E804334D5B490EA273F36830A9849ACDF|xx|yy|46|13896|9550";
$splitString=explode('|',$myString);
$xx=$splitString[1];
$yy=$splitString[2];
of course you can replicate manually with strpos, substr etc but will take more effort

Credit card Formatting function in Yii

I want to format the credit cards like below when i display it,
Eg:
1234 4567 9874 1222
as
1xxx xxxx xxx 1222
Is there any formatting function like this in Yii ?
No - but there's nothing wrong with using straight PHP.
If you always want the 1st and the last 4 chars you can do something like this:
$last4 = substr($cardNum, -4);
$first = substr($cardNum, 0, 1);
$output = $first.'xxx xxxx xxxx '.$last4;
There are many ways to do this, nothing Yii specific
You could do it using str_split (untested):
$string = "1234 4567 1234 456";
$character_array = str_split($string);
for ($i = 1; $i < count($character_array) - 4; $i++) {
if ($character_array[$i] != " "){
$character_array[$i] = "x";
}
}
echo implode($character_array);
So we are creating an array of characters from the string called
$character_array.
We are then looping thru the characters (starting from position 1,
not 0, so the first character is visible).
We loop until the number of entries in the array minus 4 (so the last
4 characters are not replaced) We replace each character in the loop
with an 'x' (if it's not equal to a space)
We the implode the array back into a string
And you could also use preg_replace :
$card='1234 4567 9874 1222';
$xcard = preg_replace('/^([0-9])([- 0-9]+)([0-9]{4})$/', '${1}xxx xxxx xxxx ${3}', $card);
This regex will also take care of hyphens.
There is no in-built function in Yii.

Adding leading 0 in php

I have
tutorial 1 how to make this
tutorial 21 how to make this
tutorial 2 how to make this
tutorial 3 how to make this
and i need
tutorial 01 how to make this
tutorial 21 how to make this
tutorial 02 how to make this
tutorial 03 how to make this
so i can order them properly. (adding leading 0 when single digit is found)
What would be a php method to convert?
thanks in advance
note-please make sure that it identifies the single digit numbers only first and then add the leading zero
str_pad()
echo str_pad($input, 2, "0", STR_PAD_LEFT);
sprintf()
echo sprintf("%02d", $input);
If it is coming from a DB, this is the way to do it on a sql query:
lpad(yourfield, (select length(max(yourfield)) FROM yourtable),'0') yourfield
This is will get the max value in the table and place the leading zeros.
If it's hardcoded (PHP), use str_pad()
str_pad($yourvar, $numberofzeros, "0", STR_PAD_LEFT);
This is a small example of what I did on a online php compiler, and it works...
$string = "Tutorial 1 how to";
$number = explode(" ", $string); //Divides the string in a array
$number = $number[1]; //The number is in the position 1 in the array, so this will be number variable
$str = ""; //The final number
if($number<10) $str .= "0"; //If the number is below 10, it will add a leading zero
$str .= $number; //Then, add the number
$string = str_replace($number, $str, $string); //Then, replace the old number with the new one on the string
echo $string;
If your goal is to do natural ordering, the way a human being would, why not just use strnatcmp
$arr = [
'tutorial 1 how to make this',
'tutorial 21 how to make this',
'tutorial 2 how to make this',
'tutorial 3 how to make this',
];
usort($arr, "strnatcmp");
print_r($arr);
The above example will output:
Array
(
[0] => tutorial 1 how to make this
[1] => tutorial 2 how to make this
[2] => tutorial 3 how to make this
[3] => tutorial 21 how to make this
)

Categories