str_replace function not working as expected - php

I'm importing data into mysql using php from a csv. I want to replace empty date fields with a date captured in a variable. I thought I could use this but it's not working:
$appt_date=str_replace('', $alt_date, $appt_date);
Any ideas why this won't work?

str_replace() is for replacing substrings within a string with something else, not for matching the whole string. You should use an if statement.
if ($appt_date == '') {
$appt_date = $alt_date;
}

Related

PHP: String Replacement not working if search string is first in line [duplicate]

This question already has an answer here:
strpos not working for a certain string
(1 answer)
Closed 1 year ago.
I'm retrieving some data from a MySQL database. For highlighting purposes, I want to modify the displayed data using PHP. A span class is added which will apply some text colouring and letter-spacing. My data is stored in $example.
This is my PHP code so far, $kw is the variable which contains the string to be replaced:
$kw = "Fun:"
if(strpos($example,$kw)) {
$example = str_replace($kw,"<span class='new'>Fun:</span>",$example);
}
This works fine for $example = "text text; Fun: text";. As for something like $example = "Fun: text";, "Fun:" is not replaced as expected, str_replace is not applied. Literally nothing happens.
When I try to replace $kw = "un:"; instead, it works fine, besides The "F" in "Fun:" is now missing the highlighting.
So if the text to be replaced is at the beginning of the search string, nothing happens. It seems that str_replace starts looking at the second character of the string instead of the beginning. I cannot figure out why.
I checked the array where the query results are stored, but found no hints which could help me solve this issue. I also printed the result from strpos for both cases. As for the first example, I got an integer > 0, for the second example the result gave 0. This seems to be fine, since in example 1 $kw is somewhere inbetween other text whereas in example 2 it is at the beginning of the line.
Did anyone ever came across this issue or am I too blind to see the solution here?
Function strpos return position of element.
If element has first position, than it's return 0 (zero).
But if statement represent zero as false. That why it's doesn't work.
Just change your if statement, like this:
//old
if(strpos($example,$kw)) {
//new
if (strpos($example,$kw) !== false) {
read more about strpos in docs
https://www.php.net/manual/ru/function.strpos.php
By the way read this
Null vs. False vs. 0 in PHP

Stringing together variables, str_replace. Tidier way to do this?

I have a bunch of variables that I want to string together. They all need to be tidied up by removing spaces and commas, and converting to dashes (I'm constructing a URL).
I have a very basic understanding of PHP, but I feel my code below could be tidier and more efficient. Could you point me to some resources or make some suggestions please?
Here's what I have:
$propNum = $prop->Address->Number;
$propStreet = $prop->Address->Street;
$propTown = $prop->Address->Town;
$propPost = $prop->Address->Postcode;
$propFullAdd = array($propNum, $propStreet, $propTown, $propPost);
$propFullAddImp = implode(" ",$propFullAdd);
$propFullAddTidy = str_replace(str_split(' ,'),'-', strtolower($propFullAddImp));
echo $propFullAddTidy;
From the output of your existing code, it seems like you may want an output that looks something like:
12345-example-street-address-example-town-example-postcode
In this case, you could use this solution:
//loop through all the values of $prop->Address
foreach($prop->Address as $value) {
//for each value, replace commas & space with dash
//store altered value in new array `$final_prop`
$final_prop[] = str_replace([' ', ','], '-', $value);
/*
Removing `str_split(' ,')` and subbing an array makes the loop "cheaper" to do,
Because the loop doesn't have to call the `str_split()` function on every iteration.
*/
}
//implode `$final_prop` array to dash separated string
//also lowercase entire string at once (cheaper than doing it in the loop)
$final_prop = strtolower(implode('-', $final_prop));
echo $final_prop;
if you remove the comments, this solution is only 4 lines (instead of 7), and is completely dynamic. This means if you add more values to $prop->Address, you don't have to change anything in this code.
A different method
I feel like this would usually be handled by using http_build_query(), which converts an array into a proper URL-encoded query string. This means that each value in the array would be passed as it's own variable in the URL query.
First, $propFullAdd is not necessary (in fact, it may be detrimental), $prop->Address already contains the exact same array. Recreating the array like this completely removes the ability to tell which value goes to which key, which could be problematic.
This means that you can simplify your entire code by replacing it with this:
echo http_build_query($prop->Address);
Which outputs something like this:
Number=12345&Street=Example+Street+Address&Town=Example+Town&Postcode=Example+Postcode

Php preg_match doesnt work with variable

I have one array which contains multiple strings. I have another array which contain also strings but they are shorter. My goal is to check is there any partial match in the bigger array for every item from the smaller array. However preg_match doesnt work at all with variables. If I put raw input everything seems fine but otherwise results is false. I have tried almost every possible regex combination but without success. Sample code:
//Lets say $needle is 3333 and bigPatern has 10 records with 10 digits each, for example third record is 5125433331. I want to perform the partial match and get true
$needle = $smlPattern[0]; //debugging with first item from smaller array
$needle2 = "/$needle/"; // I tried [$needle], ^..&, to concatenate and etc
foreach ($bigPatern as $val)
{
if (preg_match($needle2, $val))
{
echo "YES";
}
}
Any tips what Im doing wrong?
Please escape your regex input!
$needle2 = "/".preg_quote($needle,'/')."/"; //
Don't blindly add user input to your regex, much for the same reason you need to escape user input in SQL queries. In regex, the biggest issue is usually the ReDoS problem, where a malicious user can create a specially crafted regex that will use hours, or more, to execute, stealing all the CPU from your server.
Main wrong thing in your example is to use regexp for checking the presence of a string. There is a strpos function for that.
if ( strpos($bigOne, $smallOne) !== false ) {
echo "bigOne contains smallOne";
}
You can even use strpos function to achieve the same purpose. It finds the position of the first occurrence of a substring in a string, and returns false if no match is found.
$needle = $smlPattern[0];
$needle2 = "needle";
foreach ($bigPatern as $val){
if (strpos($val, $needle2) !== false){
echo "YES";
}
}

Most efficient PHP str_replace on array if row only has 5% chance of containing target?

I have a 15,000 row PHP array. I need to iterate through each row to generate a 15,000 row Javascript array. Each row of the PHP array has a 5% chance of containing one or more HTML special characters like &#243; that I need to replace with the equivalent javascript hex. There are about 50 HTML special characters I have to look out for and replace, so I'd use str_replace(array_of_HTML_targets, array_of_hex_replacements, haystack). Is it more efficient to:
Go through each line of the PHP array, search for an ampersand, and if one exists do the search and replace (considering this will apply for only 5% of the rows)
Execute the search and replace on the entire array
Concatenate the array into one giant string and execute the search and replace on the giant string
Other idea? Please specify
Btw, reason for 15,000 PHP array is this is a data visualization app.
Since you already need to dump your PHP data into a string (probably JSON), you might as well work on the final string, like so:
$json = json_encode($your_php_array);
$unhtmlref = preg_replace_callback("/&#(x[0-9a-f]+|\d+);/",function($m) {
if( $m[1][0] == "x") $m[1] = substr($m[1],1);
else $m[1] = dechex($m[1]);
return sprintf("\\u%04s",$m[1]);
},$json);
This is safe, because HTML character codes don't have any special meaning in a JSON string.
That said, I have a function in my JavaScript "utility belt" that does something similar:
function unHTMLref(str) {
// take a string and return it, with all HTML character codes parsed
var div = document.createElement('div');
div.innerHTML = str.replace(/</g,"<");
return div.firstChild.nodeValue;
}
So basically you can either parse before, or after. Personally, I'd prefer "after" because it shifts some of the "grunt" work to the browser, allowing the server to do more important things.

Replace custom tag inside a string with value from database

what I need to do is to parse a string similar to this:
{a}3{/a}*{b}4{/b}
or this
{a}3{/a}/{b}2{/b}*100
I need to substitute in that string those values within the tags with real values from the database, the first example:
SELECT value FROM table WHERE id = 3;
SELECT value FROM table WHERE id = 4;
This function:
preg_replace_callback('/(?>{([^}]+)})(.*)?{\/\1}/sim', 'find_tags_callback', $string);
Actually returns the ids contained in the string, the problem is that I'm stuck there. In pseudo code I would need to:
Extract the first id from the string.
Run my query.
Substitute that id with the correct value.
[Do the same for all tags]
Finish having back the initial string with the correct value inside.
The first might be
10*3
the second
40/90*100
Any idea how to do this, I'm completely stuck.
Thanks
Do a database query to get all the values, and put them into an array keyed off the IDs. In the code below, I assume the array is named $tags.
$new_string = preg_replace_callback('/\{([^}]+)\}(.+?)\{/\1\}/sim',
function ($match) use ($tags) {
return $tags[$match[2]];
}, $string);
The use ($tags) declaration allows the function to reference the external variable $tags.

Categories