PHP preg_replace field before bringing through from MySQL Database - php

I have a column within my MySQL database which stores a product description that includes non-alphanumeric characters. I'm trying to run a PHP dump of various fields within the datebase using my Apache Server - and I would like to remove all of the non-alphanumeric characters from the product description before being returned.
// load all stock
while ($line = mysql_fetch_assoc($result) ) {
?>
<?
$size = '3';
// check if size is available
if($line['quantity_size_'.$size.''] > 0 ) {
?>
<?=$line['product_id']?>,
<?=$line['code_size_'.$size.'']?>,
EAN,
<?=$line['title']?>,
<?=$_GET['brand']?>,
<?=$_GET['brand']?>,
**<?=$line preg_replace('/[^\da-z]/i', '', ['amazon_desc']),**
<?=$size?>,
<?=$line['colour']?>,
....
I've emboldened the relevant line above - this seems to return a T_String error.
Any body help?
Thanks
A

<?=$line preg_replace('/[^\da-z]/i', '', ['amazon_desc']),
should be:
<?=preg_replace('/[^\da-z]/i', '', $line['amazon_desc']) ?>
This basic function calling syntax, I don't know where you got the idea that you could be the array name before the function, and the index inside the arguments.

Related

Emoji name "family_mothers_one_boy" or "woman-woman-boy"?

I have a reference emojis file used by my php code. Inside there is for example "woman-woman-boy", but the browser (chrome) replaces this name by "family_mothers_one_boy"...
Why are there two versions of emojis' names?
Is there en (some) error(s) in my file, or should I have to do something in my code to avoid the conversion?
NOTE:
The code related to this emoji is:
1F469;‍👩‍&#x1F466
Here are the two functions I'm using to manage the emojis:
1. When I display the emoji, I replace the tage :name: by the HTML rendering (using unicode)
function replaceEmojiNameByUnicode($inputText){
$emoji_unicode = getTabEmojiUnicode();
preg_match_all("/:([a-zA-Z0-9'_+-]+):/", $inputText, $emojis);
foreach ($emojis[1] as $emojiname) {
if (isset($emoji_unicode[$emojiname])) {
$inputText = str_replace(":".$emojiname.":", "&#x".$emoji_unicode[$emojiname].";", $inputText);
}
else {
$inputText = str_replace(":".$emojiname.":", "(:".$emojiname.":)", $inputText);
}
}
return $inputText;
}
2. When I want to propose the list of emoji I display an HTML SELECT in the page. Teh following function return the list of option to add inside:
/* Display the options in the HTML select */
function displayEmojisOptions(){
$emoji_unicode = getTabEmojiUnicode();
foreach ($emoji_unicode as $name => $unicode) {
echo '<option value="&#x'.$unicode.';">'.$name.' => &#x'.$unicode.';</option>';
}
}
In the array $emoji_unicode there is one entry (with 3 semi-column removed to not display emoji here):
'family_one_girl' => '1F468;&#x200D&#x1F469&#x200D&#x1F467',
For example: In order to make it works, I have to replace the line 'thinking_face' => '1F914', by 'thinking' => '1F914',
My question is: why ??
Thank you
Nop, the emoji text was changed by no code... I guess it was due to a wrong emoji file I used... I correct all the emoji manually and now I did not see the mismatch anymore...
If someone need the corrected file, I can provide it.

How can I str_replace partially in PHP in a dynamic string with unknown key content

Working in WordPress (PHP). I want to set strings to the database like below. The string is translatable, so it could be in any language keeping the template codes. For the possible variations, I presented 4 strings here:
<?php
$string = '%%AUTHOR%% changed status to %%STATUS_new%%';
$string = '%%AUTHOR%% changed status to %%STATUS_oldie%%';
$string = '%%AUTHOR%% changed priority to %%PRIORITY_high%%';
$string = '%%AUTHOR%% changed priority to %%PRIORITY_low%%';
To make the string human-readable, for the %%AUTHOR%% part I can change the string like below:
<?php
$username = 'Illigil Liosous'; // could be any unicode string
$content = str_replace('%%AUTHOR%%', $username, $string);
But for status and priority, I have different substrings of different lengths.
Question is:
How can I make those dynamic substring be replaced on-the-fly so that they could be human-readable like:
Illigil Liosous changed status to Newendotobulous;
Illigil Liosous changed status to Oldisticabulous;
Illigil Liosous changed priority to Highlistacolisticosso;
Illigil Liosous changed priority to Lowisdulousiannosso;
Those unsoundable words are to let you understand the nature of a translatable string, that could be anything other than known words.
I think I can proceed with something like below:
<?php
if( strpos($_content, '%%STATUS_') !== false ) {
// proceed to push the translatable status string
}
if( strpos($_content, '%%PRIORITY_') !== false ) {
// proceed to push the translatable priority string
}
But how can I fill inside those conditionals efficiently?
Edit
I might not fully am clear with my question, hence updating the query. The issue is not related to array str_replace.
The issue is, the $string that I need to detect is not predefined. It would come like below:
if($status_changed) :
$string = "%%AUTHOR%% changed status to %%STATUS_{$status}%%";
else if($priority_changed) :
$string = "%%AUTHOR%% changed priority to %%PRIORITY_{$priority}%%";
endif;
Where they will be filled dynamically with values in the $status and $priority.
So when it comes to str_replace() I will actually use functions to get their appropriate labels:
<?php
function human_readable($codified_string, $user_id) {
if( strpos($_content, '%%STATUS_') !== false ) {
// need a way to get the $status extracted from the $codified_string
// $_got_status = ???? // I don't know how.
get_status_label($_got_status);
// the status label replacement would take place here, I don't know how.
}
if( strpos($_content, '%%PRIORITY_') !== false ) {
// need a way to get the $priority extracted from the $codified_string
// $_got_priority = ???? // I don't know how.
get_priority_label($_got_priority);
// the priority label replacement would take place here, I don't know how.
}
// Author name replacement takes place now
$username = get_the_username($user_id);
$human_readable_string = str_replace('%%AUTHOR%%', $username, $codified_string);
return $human_readable_string;
}
The function has some missing points where I currently am stuck. :(
Can you guide me a way out?
It sounds like you need to use RegEx for this solution.
You can use the following code snippet to get the effect you want to achieve:
preg_match('/%%PRIORITY_(.*?)%%/', $_content, $matches);
if (count($matches) > 0) {
$human_readable_string = str_replace("%%PRIORITY_{$matches[0]}%%", $replace, $codified_string);
}
Of course, the above code needs to be changed for STATUS and any other replacements that you require.
Explaining the RegEx code in short it:
/
The starting of any regular expression.
%%PRIORITY_
Is a literal match of those characters.
(
The opening of the match. This is going to be stored in the third parameter of the preg_match.
.
This matches any character that isn't a new line.
*?
This matches between 0 and infinite of the preceding character - in this case anything. The ? is a lazy match since the %% character will be matched by the ..
Check out the RegEx in action: https://regex101.com/r/qztLue/1

strtolower and mb_strtolower doesn't work

I have a variable in which a string is stored, which is supplied via an insert tag of the CMS Contao.
category = "{{page::title}}";
The value of the string is at this point "Fitness" with a big "F". I would like to have this string completely in lowercase letters.
I have already tried the following:
// 1
$category = "{{page::title}}";
echo strtolower($category);
// 2
$category = "{{page::title}}";
echo mb_strtolower($category);
// 3
$category = "{{page::title}}";
echo mb_strtolower($category, 'UTF-8');
But none of these approaches work and I still get "Fitness" with a big "F".
What am I doing wrong?
Insert Tags are replaced by Contao before the result is sent to the browser. You are trying to strtolower just the insert tag (which does nothing of course) - not the content it will be replaced by.
For your example you can use:
global $objPage;
echo strtolower($objPage->pageTitle ?: $objPage->title);
or
echo strtolower($GLOBALS['objPage']->pageTitle ?: $GLOBALS['objPage']->title);
or
echo strtolower(\Contao\Controller::replaceInsertTags('{{page::title}}'));

Remove Last Word in SQL row if maxlength is reached? (PHP)

A php script I have is extracting data from an XML file to a MySQL database.
It is set-up as followed:
$sql = "INSERT IGNORE INTO `tablename` (columnname) VALUES ('text text text text text text $variablename text text $variablename2 text text')
$variablename and $variablename2 are both variables being extracted from the XML file, and have varying lengths.
So, I know, if I was just dealing with PHP I could use strlen or a variation of (see How to Truncate a string in PHP to the word closest to a certain number of characters? but 'columnname' in my sql database is not a variable.
And 'columnname' is what is limited to the characters.
I set this in mySQL to VARCHAR MAX=106 -- and that works --
But when re-outputting this to my web host it takes the data from the SQL database which is stopped at the maxlength cut-off mid-word.
I want it so that if it does reach the maxlength, the last word is just removed.
Could this be done, perhaps when inputting into the SQL table?
Or even perhaps in the PHP file outputting back to my web host?, such as here:
$rs->data_seek(0);
while($res = $rs->fetch_assoc()) {
$a_topic = array(
"columnname" => $res["columnname"]
or maybe in the $params here?
$params = array(
'status' => $share['columnname'],
Big thanks!
function cut($string, $maxLength)
{
$revertString = strrev($string);
$spaceRevertedPos = strpos($revertString, ' ', strlen($string)-$maxLength);
$revertedCutString = substr($revertString, $spaceRevertedPos);
return strrev($revertedCutString);
}
DEMO

PHP Regex pattern needed for MySQL database manupilation

I have some columns in my table, descriptions column contains some information like;
a1b01,Value 1,2,1,60|a1b01,Value2,1,1,50|b203c,Value 1,0,2,20
with a SQL command, i need to update it.
In there, I'll use a PHP function for updating, if first and second parameters exist in current records (in description column) together.
Eg: if user wants to change the value of description that includes a1b01,Value 1 I'll execute a SQL command like that;
function do_action ($code,$value,$new1,$new2,$newresult) {
UPDATE the_table SET descriptions = REPLACE(descriptions, $code.','.$value.'*', $code.','.$value.','.$new1.','.$new2.','.$newresult)";
}
(star) indicates that, these part is unknown (This is why i need a regex)
My question is : how can i get
a1b01,Value 1,2,1,60|
part from below string
a1b01,Value 1,2,1,60|a1b01,Value2,1,1,50|b203c,Value 1,0,2,20
via regex, but a1b01 and Value 1 should be get as parameter.
I just want that; when I call do_action like that;
do_action ("a1b01","Value 1",2,3,25);
record will be : a1b01,Value 1,2,3,25|a1b01,Value2,1,1,50|b203c,Value 1,0,2,20(first part is updated...)
You don't necessarily need to use a regular expression to do this, you could use the explode function since it is all delimited
So you could do as follows:
$descriptionArray = explode('|', $descriptions); //creates array of the a1b01,Value 1,2,1,60 block
//then for each description explode on ,
for($i = 0; i < count($descriptionArray); $i++){
$parameters = explode(',', $descriptionArray[$i]);
do_action ($parameters[0],$parameters[1],$parameters[2],$parameters[3],$parameters[4]);
}

Categories