I need to search every word of an string in the database. If an word exist it needs to be highlighted. The current script works, but needs a lot of memory for my server. I don't know how i make it easier, but maybe do you?
<?php
$total_messages = $_POST['total'] - 1;
for($x = 0; $x <= $total_messages; $x++)
{
//Search highlights
$result = $mysqli->query("SELECT * FROM highlights WHERE enabled=1")
while($row = $result->fetch_assoc())
{
//Vars for highlights
$highlight_txt = $row['value'];
$highlight_type = $row['type'];
$highlight_color = "black";
$highlight_title = null;
//If the text isnt empty
if($highlight_txt != null || $highlight_txt != "")
{
//Type highlights
if($highlight_type == "tree") //Tree type
{
$highlight_type = "18"; //Category number
$highlight_background = "pink"; //Background
if($row['option1'] != null)
{
$highlight_title = htmlentities($row['option1']);
}
}
else
{
$highlight_background = "yellow"; //Background
}
//Add highlight
$message = preg_replace("/\b($highlight_txt)\b/i", "<span class='bc_highlight' highlight-type='$highlight_type' highlight-value='$highlight_txt' style='background: $highlight_background; color: $highlight_color;' title=''>$highlight_txt</span>", $message);
}
}
echo $message; //Display the message
}
Why not doing something like this?
$messages = ["This is my message1","This is my message2"];
$highlights = [];
$result = $mysqli->query("SELECT * FROM highlights WHERE enabled=1")
while($row = $result->fetch_assoc()) {
$highlights[$row["value"]] = [
"type" => $row["type"],
"color" => $row["color"]
];
}
$callback = function($matches) use ($highlights) {
$word = $matches[1];
if(isset($highlights[$word])) {
$highlight = $highlights[$word];
return sprintf('<span style="color:%s">%s</span>',$highlight["color"],$word);
} else {
return $word;
}
};
foreach($messages as &$message) {
$message = preg_replace_callback("/(\w+)/i",$message,$callback);
}
Related
In this code section, the query gets all the teachers and appends their assigned classes within the object
The weird thing is it works perfectly on local but not online, it is almost it doesn't wait for the while loop
<?php
$SID = mysqli_real_escape_string($con, htmlspecialchars($_POST["SID"], ENT_QUOTES));
$allTeachersArr = [];
$test = [];
$q = "SELECT onderwysers.*,klasse.Klas,klasse.Datum,klasse.Vak FROM `onderwysers` LEFT JOIN klasse ON onderwysers.ID = klasse.Teacher WHERE `SID` = '$SID'";
// echo $q;
$result = $con->query($q);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$subjectItem = new stdClass();
$filtered_array = [];
$isIn = false;
$var1 = $row['ID'];
$var2 = $row['Teacher'];
if (count($allTeachersArr) > 0)
foreach ($allTeachersArr as $item) {
if ($item->ID == $var1 && $item->Teacher == $var2) {
// do something
$filtered_array = $item;
$isIn = true;
}
}
if ($isIn == true) {
$notAdd = false;
// echo "updates";
$subjectItem->Klas = $row["Klas"];
$subjectItem->Datum = $row["Datum"];
$subjectItem->Vak = $row["Vak"];
foreach ($filtered_array->displaySubjects as $item) {
if ($item->Klas == $row["Klas"] && $item->Vak == $row["Vak"] && $item->Datum == $row["Datum"]) {
// do something
$filtered_array = $item;
$notAdd = true;
}
}
if ($notAdd == false) {
$temp = $filtered_array->displaySubjects;
array_push($temp, $subjectItem);
$filtered_array->displaySubjects = $temp;
}
} else {
//add new entry
$subjectItem->ID = $row["ID"];
$subjectItem->Title = $row["Title"];
$subjectItem->Name = $row["Name"];
$subjectItem->Surname = $row["Surname"];
$subjectItem->Afkorting = $row["Afkorting"];
$subjectItem->IdentityNumber = $row["IdentityNumber"];
$subjectItem->Geslag = $row["Geslag"];
$subjectItem->ContactDetails = $row["ContactDetails"];
$subjectItem->Email = $row["Email"];
$subjectItem->RegKlas = $row["RegKlas"];
$subjectItem->Status = $row["Status"];
$subjectItem->UID = $row["UID"];
$subjectItem->displaySubjects = [];
array_push($allTeachersArr, $subjectItem);
}
}
}
echo json_encode($allTeachersArr);
$con->close();
THE EXPECTED RETURNED DATA(This is local, online returns nothing)
I'm trying to generate auto description from tags.
The code was working but after updating my site to Laravel 6 in stop working. I need to get it back working.
if( !empty( $request->description ) )
{
$description = Helper::checkTextDb($request->description);
}
else
{
$a_key = explode(",", strtolower($request->tags));
if(count($a_key) == 0)
$description = 'This is a great thing';
else
{
$description_get_keys = '';
foreach ($a_key as &$value)
{
if($value == end($a_key) && count($a_key) != 1)
$description_get_keys = $description_get_keys.' and '.$value.'.';
else if(count($a_key) == 1)
$description_get_keys = $value.'.';
else if (count($a_key) > 1 && $a_key[0] == $value)
$description_get_keys = $value;
else
$description_get_keys = $description_get_keys.', '.$value;
}
$description = 'This is a great thing about '.$description_get_keys;
}
}
I see a couple things that could possibly be an issue, not knowing what came before this code.
I will assume that the $request variable is an instance of Illuminate\Http\Request and that it is available in the function, right?
Try this updated code:
if($request->has('description'))
{
$description = Helper::checkTextDb($request->description);
}
else if ($request->has('tags'))
{
if (strpos($request->tags, ',') === false)
{
$description = 'This is a great thing';
}
else {
$a_key = explode(",", strtolower($request->tags));
$a_count = count($a_key);
$description_get_keys = '';
for ($i = 0; $i < $a_count; $i++)
{
if ($a_count == 1) {
$description_get_keys = "{$a_key[$i]}.";
}
else {
// first
if ($i === 0) {
$description_get_keys = $a_key[0];
}
// last
else if ($i === $a_count - 1) {
$description_get_keys .= " and {$a_key[$i]}.";
}
// middle
else {
$description_get_keys .= ", {$a_key[$i]}";
}
}
}
$description = "This is a great thing about {$description_get_keys}";
}
}
I wrote that quick so hopefully there are no errors.
How increase the performance of this code in php?
or any alternative method to find out the comment if the string starts with # then call at()
or if string starts with "#" then call hash()
here the sample comment is "#hash #at #####tag";
/
/this is the comment with mention,tag
function getCommentWithLinks($comment="#name #tag ###nam1 test", $pid, $img='', $savedid='', $source='', $post_facebook='', $fbCmntInfo='') {
//assign to facebook facebookComment bcz it is used to post into the fb wall
$this->facebookComment = $comment;
//split the comment based on the space
$comment = explode(" ", $comment);
//get the lenght of the splitted array
$cmnt_length = count($comment);
$store_cmnt = $tagid = '';
$this->img = $img;
$this->saveid = $savedid;//this is uspid in product saved table primary key
//$this->params = "&product=".base_url()."product/".$this->saveid;
$this->params['product'] = base_url()."product/".$this->saveid;
//$this->params['tags']='';
foreach($comment as $word) {
//check it is tag or not
//the first character must be a # and remaining all alphanumeric if any # or # is exist then it is comment
//find the length of the tag #mention
$len = strlen($word);
$cmt = $c = $tag_name = '';
$j = 0;
$istag = false;
for($i=0; $i<$len; $i++) {
$j = $i-1;
//check if the starting letter is # or not
if($word[$i] == '#') {
//insert tagname
if($istag) {
//insert $tag_name
$this->save_tag($tag_name, $pid);
$istag = false;
$tag_name = '';
}
//check for comment
if($i >= 1 && $word[$j]=='#') {
$this->store_cmnt .= $word[$i];
}else{
//append to the store_coment if the i is 1 or -1 or $word[j]!=#
$this->store_cmnt .= $word[$i];//23,#
}
}else if($word[$i]=='#') {
//insert tagname
if($istag) {
//insert $tag_name
$this->save_mention($tag_name, $pid, $fbCmntInfo);
$istag = false;
$tag_name = '';
}
//check for comment
if($i >= 1 && $word[$j]=='#') {
$this->store_cmnt .= $word[$i];
}else{
$this->store_cmnt .= $word[$i];//23,#
}
}else if( $this->alphas($word[$i]) && $i!=0){
if($tag_name=='') {
//check the length of the string
$strln=strlen($this->store_cmnt);//4
if($strln != 0) {
$c = substr($this->store_cmnt, $strln-1, $strln);//#
if($c=='#' || $c=='#') {
$this->store_cmnt = substr($this->store_cmnt, 0, $strln-1);//23,
$tag_name = $c;
}
}
//$tag_name='';
}
//check that previous is # or # other wise it is
if($c=='#' || $c=='#') {
$tag_name .= $word[$i];
$istag = true;
//check if lenis == i then add anchor tag her
if($i == $len-1) {
$istag =false;
//check if it is # or #
if($c=='#')
$this->save_tag($tag_name,$pid);
else
$this->save_mention($tag_name,$pid,$fbCmntInfo);
//$this->store_cmnt .= '<a >'. $tag_name.'</a>';
}
}else{
$this->store_cmnt .= $word[$i];
}
}else{
if($istag) {
//insert $tag_name
$this->save_tag($tag_name,$pid);
$istag = false;
$tag_name = '';
}
$this->store_cmnt .= $word[$i];
}
}
$this->store_cmnt .=" ";
}
}
Try This it may be help full
function getResultStr($data, $param1, $param2){
return $param1 != $param2?(''.$data.''):$data;
}
function parseWord($word, $symbols){
$result = $word;
$status = FALSE;
foreach($symbols as $symbol){
if(($pos = strpos($word, $symbol)) !== FALSE){
$status = TRUE;
break;
}
}
if($status){
$temp = $symFlag = '';
$result = '';
foreach(str_split($word) as $char){
//Checking whether chars are symbols(#,#)
if(in_array($char, $symbols)){
if($symFlag != ''){
$result .= getResultStr($temp, $symFlag, $temp);
}
$symFlag = $temp = $char;
} else if(ctype_alnum($char) or $char == '_'){
//accepts[0-9][A-Z][a-z] and unserscore (_)
//Checking whether Symbol already started
if($symFlag != ''){
$temp .= $char;
} else {
//Just appending the char to $result
$result .= $char;
}
} else {
//accepts all special symbols excepts #,# and _
if($symFlag != ''){
$result .= getResultStr($temp, $symFlag, $temp);
$temp = $symFlag = '';
}
$result .= $char;
}
}
$result .= getResultStr($temp, $symFlag, '');
}
return $result;
}
function parseComment($comment){
$str = '';
$symbols = array('#', '#');
foreach(explode(' ', $comment) as $word){
$result = parseWord($word, $symbols);
$str .= $result.' ';
}
return $str;
}
$str = "#Richard, #McClintock, a Latin professor at $%#Hampden_Sydney #College-in #Virginia, looked up one of the ######more obscure Latin words, #######%%#%##consectetur, from a Lorem Ipsum passage, and #going#through the cites of the word in classical literature";
echo "<br />Before Parsing : <br />".$str;
echo "<br /><br />After Parsing : <br />".parseComment($str);
use strpos or preg_match or strstr
Please refer string functions in php. You can do it in a line or two with that in built functions.
If it not matches better to write a regex.
I am trying to integrate php bad words filter
The input is taken through $_REQUEST['qtitle'] and $_REQUEST['question']
But I am failed to do so
$USERID = intval($_SESSION['USERID']);
if ($USERID > 0)
{
$sess_ver = intval($_SESSION[VERIFIED]);
$verify_asker = intval($config['verify_asker']);
if($verify_asker == "1" && $sess_ver == "0")
{
$error = $lang['225'];
$theme = "error.tpl";
}
else
{
$theme = "ask.tpl";
STemplate::assign('qtitle',htmlentities(strip_tags($_REQUEST['qtitle']), ENT_COMPAT, "UTF-8"));
STemplate::assign('question',htmlentities(strip_tags($_REQUEST['question']), ENT_COMPAT, "UTF-8"));
if($_REQUEST['subform'] != "")
{
$qtitle = htmlentities(strip_tags($_REQUEST['qtitle']), ENT_COMPAT, "UTF-8");
$question = htmlentities(strip_tags($_REQUEST['question']), ENT_COMPAT, "UTF-8");
$category = intval($_REQUEST['category']);
if($qtitle == "")
{
$error = $lang['3'];
}
elseif($category <= "0")
{
$error = $lang['4'];
}
else
{
if($config['approve_stories'] == "1")
{
$addtosql = ", active='0'";
}
$query="INSERT INTO posts SET USERID='".mysql_real_escape_string($USERID)."', title='".mysql_real_escape_string($qtitle)."',question='".mysql_real_escape_string($question)."', tags='".mysql_real_escape_string($qtitle)."', category='".mysql_real_escape_string($category)."', time_added='".time()."', date_added='".date("Y-m-d")."' $addtosql";
$result=$conn->execute($query);
$userid = mysql_insert_id();
$message = $lang['5'];
}
}
}
}
else
{
$question = htmlentities(strip_tags($_REQUEST['qtitle']), ENT_COMPAT, "UTF-8");
$redirect = base64_encode($thebaseurl."/ask?qtitle=".$question);
header("Location:$config[baseurl]/login?redirect=$redirect");exit;
}
I am trying the following code but this code replaces every word (which is not included in the array)
FUNCTION BadWordFilter(&$text, $replace){
$bads = ARRAY (
ARRAY("butt","b***"),
ARRAY("poop","p***"),
ARRAY("crap","c***")
);
IF($replace==1) { //we are replacing
$remember = $text;
FOR($i=0;$i<sizeof($bads);$i++) { //go through each bad word
$text = EREGI_REPLACE($bads[$i][0],$bads[$i][1],$text); //replace it
}
IF($remember!=$text) RETURN 1; //if there are any changes, return 1
} ELSE { //we are just checking
FOR($i=0;$i<sizeof($bads);$i++) { //go through each bad word
IF(EREGI($bads[$i][0],$text)) RETURN 1; //if we find any, return 1
}
}
}
$qtitle = BadWordFilter($wordsToFilter,0);
$qtitle = BadWordFilter($wordsToFilter,1);
What I am missing here?
I agree with #Gordon that this is reinventing the wheel, but if you really want to do it, here's a better start:
function badWordFilter(&$text, $replace)
{
$patterns = array(
'/butt/i',
'/poop/i',
'/crap/i'
);
$replaces = array(
'b***',
'p***',
'c***'
);
$count = 0;
if($replace){
$text = preg_replace($patterns, $replaces, $text, -1, $count);
} else {
foreach($patterns as $pattern){
$count = preg_match($pattern, $text);
if($count > 0){
break;
}
}
}
return $count;
}
There are lots of inherent issues, though. For instance, run the filter on the text How do you like my buttons? ... You'll end up with How do you like my b***ons?
I think you should use this kind of function :
function badWordsFilter(&$text){
$excluded_words = array( 'butt', 'poop', 'crap' );
$replacements = array();
$i = count($excluded_words);
while($i--){
$tmp = $excluded_words{0};
for($i=0;$i<(strlen($excluded_words)-1);$i++){
$tmp .= '*';
}
$replacements[] = $tmp;
}
str_replace($excluded_words, $replacements, $text);
}
I'm developing a system for a client that creates a csv of packing labels which is sent to a printer. The client has six different items. Customers order products in bulk from my client. Two items (product A and product B) share the same packing line. In order to make packing more efficient my client wants to alternate between packing product A and packing product B first.
For example, if John, Sally, and James all ordered both products, the system needs to write John's orders to the csv starting with product A, Sally's orders starting with product B, and James' orders starting with product A again.
I've pasted my non-working code below, but this is really screwing with my head and I'm having a really tough time with it.
foreach($orders as $order) {
$name = null;
$phone = null;
$account = DAO_ContactPerson::get($order->account_id);
$delivery = false;
if($account->is_agency) {
$name = $order->getAttribute('name');
$phone = $order->getAttribute('phone');
} else {
$name = sprintf("%s %s",
$account->getPrimaryAddress()->first_name,
$account->getPrimaryAddress()->last_name
);
$phone = $account->phone;
}
$name = trim($name);
$phone = trim($phone);
$items = $order->getItems();
if($order->getAttribute('delivery')) {
$type = 'deliveries';
$destination = 'Delivery';
$address = sprintf("%s %s %s",
$order->getAttribute('delivery_address.line1'),
$order->getAttribute('delivery_address.line2'),
$order->getAttribute('delivery_address.postal')
);
} else {
$type = 'pickups';
$agency = DAO_ContactPerson::getAgency($order->getAttribute('pickup'));
$destination = $agency->name;
// Override account id so orders are grouped by agency
$order->account_id = $agency->id;
$address = null;
}
// var_dump($order->id);
// Init account array
if(!isset($rows[$type][$order->account_id]))
$rows[$type][$order->account_id] = array('combined' => array(), 'separate' => array());
foreach($items as $item) {
$packing = 'separated';
if($item->product_id == 3 || $item->product_id == 4)
$packing = 'combined';
if(!isset($rows[$type][$order->account_id][$packing][$item->product_id]))
$rows[$type][$order->account_id][$packing][$item->product_id] = array();
$i = 0;
while($i < $item->quantity) {
$rows[$type][$order->account_id][$packing][$item->product_id][] = array(
'number' => $order->id,
'destination' => $destination,
'size' => $item->product_id,
'name' => $name,
'address' => $address,
'phone' => $phone
);
$i++;
}
}
// if($order->id == 176) {
// var_dump($rows[$type][$order->account_id][$packing]);
// }
}
$this->weight = 1;
$pickups = count($rows['pickups']);
for($i = 0; $i < $pickups; $i++) {
$account =& $rows['pickups'][$i];
$account['output'] = array();
if(isset($account['combined'])) {
$combined_products =& $account['combined'];
if(!empty($combined_products)) {
foreach($combined_products as $prod_id => $combined) {
usort($combined_products[$prod_id], array($this, "_compareBoxes"));
}
// Flip weights once we finish with this account
$last_box = end($combined_products);
$last_box = array_pop($last_box);
reset($combined_products);
if($this->weight == 1) {
$this->weight = -1;
if($last_box['size'] == 3) {
asort($combined_products);
}
} else {
if($last_box['size'] == 4) {
arsort($combined_products);
}
$this->weight = 1;
}
foreach($combined_products as $combined) {
$account['output'][] = $combined;
}
foreach($account['separated'] as $separate) {
$account['output'][] = $separate;
}
}
} else {
if(isset($account['separated']))
$account['output'] = $account['separated'];
}
}
$deliveries = count($rows['deliveries']);
for($i = 0; $i < $deliveries; $i++) {
$account =& $rows['deliveries'][$i];
$account['output'] = array();
if(isset($account['combined'])) {
$combined_products =& $account['combined'];
if(!empty($combined_products)) {
foreach($combined_products as $prod_id => $combined) {
usort($combined_products[$prod_id], array($this, "_compareBoxes"));
}
// Flip weights once we finish with this account
$last_box = end($combined_products);
$last_box = array_pop($last_box);
reset($combined_products);
if($this->weight == 1) {
$this->weight = -1;
if($last_box['size'] == 3) {
asort($combined_products);
}
} else {
if($last_box['size'] == 4) {
arsort($combined_products);
}
$this->weight = 1;
}
foreach($combined_products as $combined) {
$account['output'][] = $combined;
}
foreach($account['separated'] as $separate) {
$account['output'][] = $separate;
}
}
} else {
if(isset($account['separated']))
$account['output'] = $account['separated'];
}
}
$rows['output'] = $rows['pickups'];
array_push($rows['output'], $rows['deliveries']);
$output = '';
foreach($rows['output'] as $account_id => $boxes) {
if(!empty($boxes['output'])) {
foreach($boxes['output'] as $labels) {
if(!empty($labels)) {
foreach($labels as $label) {
$output .= implode(',', $label) . "<br>";
}
}
}
}
}
The _compareBoxes method looks like this:
private function _compareBoxes($a, $b) {
if($a['size'] == $b['size']) {
return 0;
}
if($this->weight == 1) {
// Medium first, then Large
return ($a['size'] < $b['size']) ? -1 : 1;
}
if($this->weight == -1) {
// Large first, then Medium
return ($a['size'] > $b['size']) ? -1 : 1;
}
}