Im trying to filter some entry's in a While loop. This i'm trying to do with the strpos function, unfortunately when i use a variable as needle, i do not get an result.
No result:
$tra = strpos($HRreq, $entry_type)
result: $tra = strpos($HRreq, "string");
But, i need it to be variable in the while loop.
$select_exec = odbc_exec($amos_db,$select_personnel);
while ($row = odbc_fetch_array($select_exec)){
$username = $row['user_sign'];
$entry_type = $row['entry_type'];
$fullname1 = $row['lastname'] . $row['firstname'];
$fullname = trim(preg_replace('/ +/', ' ', preg_replace('/[^A-Za-z0-9 ]/', ' ', urldecode(html_entity_decode(strip_tags($fullname1))))));
$userno = $row['employee_no_i'];
$tra = strpos($HRreq, "$entry_type");
echo $entry_type ." = ". $tra;
}
I've added part of the code since the code is more than 500 lines long. I hope this is enough to get an idea of what i'm trying to accomplish
I discovered that the database returned with white spaces after the variable. I added a trim() and the problem was solved. It was a silly mistake.
Related
I have a very long list of names and I am using preg_replace to match if a name from the list is anywhere in the string. If I test it with few names in the regex it works fine, but having in mind that I have over 5000 names it gives me the error "preg_replace(): Compilation failed: regular expression is too large".
Somehow I cannot figure out how to split the regex into pieces so it becomes smaller (if even possible).
The list with names is created dynamically from a database. Here is my code.
$query_gdpr_names = "select name FROM gdpr_names";
$result_gdpr_names = mysqli_query($connect, $query_gdpr_names);
while ($row_gdpr_names = mysqli_fetch_assoc($result_gdpr_names))
{
$AllNames .= '"/'.$row_gdpr_names['name'].'\b/ui",';
}
$AllNames = rtrim($AllNames, ',');
$AllNames = "[$AllNames]";
$search = preg_replace($AllNames, '****', $search);
The created $AllNames str looks like this (in the example 3 names only)
$AllNames = ["/Lola/ui", "/Monica\b/ui", "/Chris\b/ui"];
And the test string
$search = "I am Lola and my friend name is Chris";
Any help is very appreciated.
Since it appears that you can't easily handle the replacement from PHP using a single regex alternation, one alternative would be to just iterate each name in the result set one by one and make a replacement:
while ($row_gdpr_names = mysqli_fetch_assoc($result_gdpr_names)) {
$name = $row_gdpr_names['name'];
$regex = "/\b" . $name . "\b/ui";
$search = preg_replace($regex, '----', $search);
}
$search = preg_replace("/----/", '****', $search);
This is not the most efficient pattern for doing this. Perhaps there is some way you can limit your result set to avoid a too long single alternation.
Ok, I was debugging a lot. Even isolating everything else but this part of code
$search = "Lola and Chris";
$query_gdpr_names = "select * FROM gdpr_names";
$result_gdpr_names = mysqli_query($connect, $query_gdpr_names);
while ($row_gdpr_names = mysqli_fetch_assoc($result_gdpr_names)) {
$name = $row_gdpr_names['name'];
$regex = "/\b" . $name . "\b/ui";
$search = preg_replace($regex, '****', $search);
}
echo $search;
Still, print inside but not outside the loop.
The problem actually was in the database records. There was a slash in one of the records
I have a string with a large list with items named as follows:
str = "f05cmdi-test1-name1
f06dmdi-test2-name2";
So the first 4 characters are random characters. And I would like to have an output like this:
'mdi-test1-name1',
'mdi-test2-name2',
As you can see the first characters from the string needs to be replaced with a ' and every line needs to end with ',
How can I change the above string into the string below? I've tried for ours with 'strstr' and 'str_replace' but I can't get it working. It would save me a lot of time if I got it work.
Thanks for your help guys!
Here is a way to do the job:
$input = "f05cmdi-test1-name1
f05cmdi-test2-name2";
$result = preg_replace("/.{4}(\S+)/", "'$1',", $input);
echo $result;
Where \S stands for a NON space character.
EDIT : I deleted the above since the following method is better and more reliable and can be used for any possible combination of four characters.
So what do I do if there are a million different possibillites as starting characters ?
In your specific example I see that the only space is in between the full strings (full string = "f05cmdi-test1-name1" )
So:
str = "f05cmdi-test1-name1 f06dmdi-test2-name2";
$result_array = [];
// Split at the spaces
$result = explode(" ", $str);
foreach($result as $item) {
// If four random chars take string after the first four random chars
$item = substr($item, 5);
$result_array = array_push($result_arrray, $item);
}
Resulting in:
$result_array = [
"mdi-test1-name1",
"mdi-test2-name2",
"....."
];
IF you would like a single string in the style of :
"'mdi-test1-name1','mdi-test2-name2','...'"
Then you can simply do the following:
$result_final = "'" . implode("','" , $result_array) . "'";
This is doable in a rather simple regex pattern
<?php
$str = "f05cmdi-test1-name1
f05cmdi-test2-name2";
$str = preg_replace("~[a-z0-9]{1,4}mdi-test([0-9]+-[a-z0-9]+)~", "'mdi-test\\1',", $str);
echo $str;
Alter to your more specific needs
I am stuck with a problem, I have fetched some values from a MySQL query and put them in to an array like so:
$add1 = $location->address1;
$add2 = $location->address2;
$twn = $location->town;
$pcode = $location->postcode;
$latitude = $location->lat;
$longitude = $location->lng;
$fullAddress = [$add1, $add2, $twn, $pcode];
$string = rtrim(implode(',', $fullAddress), ',');
echo $string;
so that I can echo out a users address. The problem I am getting is that even if one of these values does not exist (and some don't because they are not all required fields), the comma is still echoed to the screen like:
add1,, town, br2 5lp
because there is an empty value in the database.
What I want to achieve is something like:
add1, town, br2 5lp
if the second part of the address is missing.
Can anyone help me figure this out?
try this.
$fullAddress = [$add1, $add2, $twn, $pcode];
$string = implode(',', array_filter($fullAddress, 'strlen'));
echo $string;
The problem I am getting is that even if one of these values does not
exist (and some dont because they are not all required fields),
the comma is still echoed to the screen
That is what the implode function in php is supposed to do. If you want a different behavior, you will have to either change the way you create your CSV string or do some extra processing on the information you obtain from the implode function.
So use a for loop or a foreach loop to go through the address array. A for loop is faster than a foreach loop.
Using Foreach:
$add1 = $location->address1;
$add2 = $location->address2;
$twn = $location->town;
$pcode = $location->postcode;
$latitude = $location->lat;
$longitude = $location->lng;
$fullAddress = [$add1, $add2, $twn, $pcode];
$string = "";
foreach($fullAddress as $value)
{
if(!empty($value))
$string .= $value.", ";
}
$string = rtrim($string, ", ");
echo $string;
You can do some extra processing on the created csv string of your own solution by maybe doing a str_replace() of all occurances of ,, with ,. This could be dangerous because if any of the values in your $fullAddress array contain a ,, as a valid string then that will also be replaced too with ,.
What you need is to assure array $fullAddress have no empty value, so php built-in function array_filter make this purpose very easy.
Just change your last codes to:
$string = implode(',', array_filter($fullAddress));
echo $string;
If the second parameter of array_filter is not supplied, all entries of array equal to FALSE will be removed. So just simply use array_filter($fullAddress) it make the code more clear and simple.
I'm attempting to concatenate two values from a serialized array. I have this working well. The problem is one of the values Size in this case, contains white-space. I need to remove this whitespace. I have used preg_match before to remove the white-space from a variable/string. The problem I have here is how I might implement preg_match in this instance, if it is the correct approach.
foreach($contents as $item)
{
$save = array();
$item = unserialize($item);
**$item['sku'] = $item['sku'] . '' . $item['options']['Size'];**
//echo '<pre>';
//print_r($item['sku']);
//exit();
$save['contents'] = serialize($item);
$save['product_id'] = $item['id'];
$save['quantity'] = $item['quantity'];
$save['order_id'] = $id;
$this->db->insert('order_items', $save);
}
Many thanks.
PHP has function named trim() that allows trimming strings.
You can simply use str_replace like this:
$item['sku'] .= ' ' . str_replace(' ', '', $item['options']['Size']);
I try to pull out the number string from google and clean it up.
<?php
$q="35 meter in inch";
$query = explode (" ",$q);
$googleUrl="http://www.google.com/search?q=$query[0]+$query[1]+$query[2]+$query[3]";
$package = file_get_contents("$googleUrl");
$content = preg_replace('/.*<h2[^>]* style="font-size:138%"><b>|<\/b><\/h2>.*/si', "", $package) ;
$number = explode (" ",$content);
$result = str_replace(' ','',$number[3]);
echo $result;
?>
however, the number i've got has a space.
I tried to replace it with needles " " or "  ;". Or utf8_encode, decode $content. None of them works.
As for the solution to your problem, the best answer is to replace anything that is not a number or punctuation using preg_replace(); Try this:
<?php
$q="35 meter in inch";
$query = explode (" ",$q);
$googleUrl="http://www.google.com/search?q=$query[0]+$query[1]+$query[2]+$query[3]";
$package = file_get_contents("$googleUrl");
$content = preg_replace('/.*<h2[^>]* style="font-size:138%"><b>|<\/b><\/h2>.*/si', "", $package) ;
$number = explode (" ",$content);
$result = preg_replace("/[^\d.]/", '', $number[3]);
echo $result;
?>
But you may want to look into using google.com/ig/calculator. It should save a lot on bandwidth and save you having to pull a full Google Results page and replace on it: http://www.google.com/ig/calculator?hl=en&q=35%20meter%20in%20inch
<?php
$q="35 meter in inch";
$query = explode (" ",$q);
$googleUrl="http://www.google.com/ig/calculator?q=$query[0]+$query[1]+$query[2]+$query[3]";
$content = file_get_contents("$googleUrl");
preg_match("/rhs:\s\"(.*)\",error/", $content, $number);
$num = explode(" ", $number[1]);
$num = preg_replace("/[^\d.]/", '', $num[0]);
echo $num;
?>
Probably because it's not really a space, even though it looks like it. You could try replacing all \w with the regular expression.
hi the space before <?php tag it it there in your code too? then that might be giving the space check that!
This is not a space you are trying to remove, it is "à" that is not visible in browser. You can also check these things by using your php script by commandline. You can use html entities function and then replace according to that