How to use preg_replace_callback - preg-replace-callback

I am trying to replace the 2nd occurrence of the $target_str.
If someone could explain how preg_replace_callback works I would appreciate it.
I don't understand the function($match) part. How do I set it so it matches the 2nd occurrence and only replaces that string?
I have the code (but it doesn't work as I want it to).
$replacement_params['target_str'] = "[\n]";
$replacement_params['replacement_str'] = "\n<ads media=googleAds1 />\n";
$target_str = $this->params['target_str'];
$replacement_str = $this->params['replacement_str'];
$num_matches;
$i = 0;
$new_text = preg_replace_callback("/".$target_str."/U",
function ( $match ) {
if ( $i === 1 ) {
return $replacement_str;
} else {
return $match[0];
}
$i++;
} , $article_text, 1, $num_matches );

Updated
Using built-in counter variable of preg_replace_callback:
$new_text = preg_replace_callback("/$target_str/U",
function($matches) use (&$count, $replacement_str)
{
$count++;
return ($count == 2) ? $replacement_str : $matches[0];
} , $article_text, -1, $count);

Related

How to pluck a value from foreach statement in Laravel

I am getting an array from database table and through a for each statement. Then check the difference between two values if there is any difference that is less than zero sets a value to 0 for that loop. Then do the same with the next loop.
$bom_id = App\Models\Bom::where('item_id', $item->order_item->id)->pluck('id')->first();
if ($bom_id > 0) {
$bomList = App\Models\Bom_list::where('bom_id', $bom_id)->get();
echo '<div class="row">';
foreach ($bomList as $bomlist) {
$availableQty = $item->order_item->qty;
$requiredQty = $bomlist->qty * $item->qty;
$dif = $availableQty - $requiredQty;
}
$check = '';
$arr = array($bomlist->$dif);
$light = in_array($check, $arr, true) ? 0 : 1;
} else {
$light = 0;
}
enter image description here

How to add another array value in codeigniter using getRecords

The orignial code was like this , I want to get landline_no value also in getRecords, How to do that
public function checklead() {
$lead = $_POST['number'];
$check = $this->common_model->getRecords('leads',array("phone_no"=>$lead));
if(count($check) > 0) {
$lead = $this->common_model->getRecored_row('leads',array("phone_no"=>$lead));
if($lead->assignto_self != 0) {
$assignto = $lead->assignto_self;
$key = 'Self Assign';
} else if($lead->assignto_se != 0) {
$assignto = $lead->assignto_se;
$key = '';}
What I have achieved so far,but not getting array values from getRecords
$lead = $_POST['number'];
$check = $this->common_model->getRecords('leads',array("phone_no"=>$lead),array("landline_no"=>$lead));
//echo "<pre>";
//print_r($check);
//echo $check[0]['landline_no'];exit;
if(count($check) > 0) {
$lead = $this->common_model->getRecored_row('leads',array("phone_no"=>$lead,"landline_no"=>$check[0]['landline_no']));
Code for getRecords:
function getRecords($table,$db = array(),$select = "*",$ordercol = '',$group = '',$start='',$limit=''){
$this->db->select($select);
if(!empty($ordercol)){
$this->db->order_by($ordercol);
}
if($limit != '' && $start !=''){
$this->db->limit($limit,$start);
}
if($group != ''){
$this->db->group_by($group);
}
$q=$this->db->get_where($table, $db);
return $q->result_array();
}
// Get Recored row
public function getRecored_row($table,$where)
{
$q = $this->db->where($where)
->select('*')
->get($table);
return $q->row();
}
Check my answer: This code also working well, i have written, but i am not sure , this logic is correct or not kindly check this one.
public function checklead() {
$lead = $_POST['number'];
if($this->common_model->getRecords('leads',array("phone_no"=>$lead)))
{
$check=$this->common_model->getRecords('leads',array("phone_no"=>$lead));
}
else
{
$check=$this->common_model->getRecords('leads',array("landline_no"=>$lead));
}
echo "<pre>";
//echo $check;
//print_r($check); exit;
$p= $check[0]['phone_no'];
$l= $check[0]['landline_no'];
// exit;
if(count($p) > 0 || count($l)>0) {
$lead = $this->common_model->getRecored_row('leads',array("phone_no"=>$p));
$lead1 = $this->common_model->getRecored_row('leads',array("landline_no"=>$l));
if($lead->assignto_self != 0 || $lead1->assignto_self != 0) {
$assignto = $lead->assignto_self;
$key = 'Self Assign';
} else if($lead->assignto_se != 0 || $lead1->assignto_se != 0) {
$assignto = $lead->assignto_se;
$key = '';
}else if($lead->assignto_tl != 0 || $lead1->assignto_tl != 0) {
$assignto = $lead->assignto_tl;
$key = '';
} else if($lead->uploaded_by != 0 || $lead1->uploaded_by != 0) {
$assignto = $lead->uploaded_by;
$key = 'Uploaded by';
}
$user = $this->common_model->getRecored_row('admin',array("id"=>$assignto));
$role = $this->common_model->getRecored_row('role',array("id"=>$user->role));
$this->session->set_flashdata('message', array('message' => 'This Lead Already exist with '.$user->name.' ('.$role->role.') '.' ','class' => 'danger'));
redirect(base_url().'leads');
} else {
redirect(base_url().'leads/add_newlead/'.$lead);
}
}
There does not seem to be any reason to use getRecords(). The $check value has no useful purpose and creating it is a waste of resources.
We don't need $check because getRecord_row() will return the "lead" if found so the only check needed is to see if getRecord_row() returns anything. getRecord_row() uses the database function row() which returns only one row or null if no rows are found. Read about row() here.
If what you want is to find the "lead" that has either a "phone_no" or a "landline_no" equal to $_POST['number'] then you need to use a custom string for the where clause. (See #4 at on this documentation page.) You need a custom string because getRecord_row() does not allow any other way to ask for rows where a='foo' OR b='foo'. Here is what I think you are looking for.
public function checklead()
{
// use input->post() it is the safe way to get data from $_POST
$phone = $this->input->post('number');
// $phone could be null if $_POST['number'] is not set
if($phone)
{
$lead = $this->common_model->getRecored_row('leads', "phone_no = $phone OR landline_no = $phone");
// $lead could be null if nothing matches where condition
if($lead)
{
if($lead->assignto_self != 0)
{
$assignto = $lead->assignto_self;
$key = 'Self Assign';
}
else if($lead->assignto_se != 0)
{
$assignto = $lead->assignto_se;
$key = '';
}
}
}
}
The main difference between getRecords() and getRecord_row() is the number of records (rows of data) to return. getRecord_row() will return a maximum of one record while getRecords() might return many records.
getRecords() accepts arguments that allow control of what data is selected ($db, $select), how it is arranged ($ordercol, $group), and the number of rows to retrieve ($limit) starting at row number x ($start) .

doctrine query with parameters having multiple values

I want to make a doctrine query in which each parameters can have multiple values (coming from a select multiple).
I have a table with a 'type' parameter that can have value of 1, 2, 3 or 4 and an 'online' parameter that can be 0 or 1.
My query so far is the following :
$query = $this->createQueryBuilder('properties');
if (array_key_exists('type', $searchValues)) {
$types = $searchValues['type'];
$iterator = 0;
foreach ($types as $type) {
if ($iterator == 0) {
$query->andWhere('properties.idPropertyType = ' . $type);
} else {
$query->orWhere('properties.onlineProperties = ' . $type);
}
$iterator++;
}
}
if (array_key_exists('status', $searchValues)) {
$status = $searchValues['status'];
$iterator = 0;
foreach ($status as $statu) {
if ($iterator == 0) {
$query->andwhere('properties.onlineProperties = ' . $statu);
} else {
$query->andWhere('properties.onlineProperties = ' . $statu);
}
$iterator++;
}
}
$properties = $query->getQuery()->getResult();
In the case of a search with parameter type = 1 and online = 0 and 1, I have results where type is another value than 1. I understand the reason why but I cannot figure out a proper way to make my query.
You don't need to build your query by hand manually, just use the (in) function from the QueryBuilder class. Try this:
$query = $this->createQueryBuilder('properties');
if(array_key_exists('type', $searchValues)){
$types = $searchValues['type'];
$query->andWhere($query->expr()->in('properties.idPropertyType', $types));
}
if(array_key_exists('status', $searchValues)){
$status = $searchValues['status'];
$query->andwhere($query->expr()->in('properties.onlineProperties', $status));
}
$properties = $query->getQuery()->getResult();

Laravel Model Average of Non-N/A Values

I am looking for the best way to average the values of a submodel in Laravel, but ignore some of the values. The column I want to average is set as varchar, but contains either a number between 0 and 10 or the value 'N/A'. I need two averages on this column, one ignoring 'N/A' values, and one counting 'N/A' values as 0. I have the fucntions written how how they would be to calculate the averages but I am hoping to get some input on the best way to do this.
I would love to be able to call these functions like this:
$web_scored_tq = $website->scored_tq;
$web_uscored_tq = $website->unscored_tq;
Functions:
public function scored_tq() {
$valid_click_ads = $this->valid_click_ads;
$total = 0;
$num = 0;
foreach ($valid_click_ads as $valid_click_ad) {
if ($valid_click_ad->tq != "N/A") {
$total += $valid_click_ad->tq;
++$num;
}
}
$scored_tq = $total / $num;
}
public function unscored_tq() {
$valid_click_ads = $this->valid_click_ads;
$total = 0;
$num = 0;
foreach ($valid_click_ads as $valid_click_ad) {
if ($valid_click_ad->tq != "N/A") {
$total += $valid_click_ad->tq;
++$num;
} else {
++$num;
}
}
$unscored_tq = $total / $num;
}
I found laravel's model getFooAttribute! I used this to add the following functions to my Website model, and now can call $website->scored_tq or $website->unscored_tq.
public function getScoredTqAttribute() {
$valid_click_ads = $this->valid_click_ads;
$total = 0;
$num = 0;
foreach ($valid_click_ads as $valid_click_ad) {
if ($valid_click_ad->tq != -1) {
$total += $valid_click_ad->tq;
++$num;
}
}
if ( $num != 0 ) {
$scored_tq = $total / $num;
} else {
$scored_tq = '-';
}
return $scored_tq;
}
public function getUnscoredTqAttribute() {
$valid_click_ads = $this->valid_click_ads;
$total = 0;
$num = 0;
foreach ($valid_click_ads as $valid_click_ad) {
if ($valid_click_ad->tq != -1) {
$total += $valid_click_ad->tq;
}
++$num;
}
if ( $num != 0 ) {
$unscored_tq = $total / $num;
} else {
$unscored_tq = '-';
}
return $unscored_tq;
}
I also changed how my data is structured to integers, where "N/A" values are changed to -1.

How to prevent users from registering using diffrent characters than arabic with regex ?)

I want to prevent my visitors who want to become users in my websites from using Latin characters.
I want them to use only Arabic user names.
How to do that with regex and preg_match?
I think this has been answered here -> stackoverflow.com - How do I detect if an input string is Arabic
<?
function uniord($u) {
// i just copied this function fron the php.net comments, but it should work fine!
$k = mb_convert_encoding($u, 'UCS-2LE', 'UTF-8');
$k1 = ord(substr($k, 0, 1));
$k2 = ord(substr($k, 1, 1));
return $k2 * 256 + $k1;
}
function is_arabic($str) {
if(mb_detect_encoding($str) !== 'UTF-8') {
$str = mb_convert_encoding($str,mb_detect_encoding($str),'UTF-8');
}
/*
$str = str_split($str); <- this function is not mb safe, it splits by bytes, not characters. we cannot use it
$str = preg_split('//u',$str); <- this function woulrd probably work fine but there was a bug reported in some php version so it pslits by bytes and not chars as well
*/
preg_match_all('/.|\n/u', $str, $matches);
$chars = $matches[0];
$arabic_count = 0;
$latin_count = 0;
$total_count = 0;
foreach($chars as $char) {
//$pos = ord($char); we cant use that, its not binary safe
$pos = uniord($char);
echo $char ." --> ".$pos.PHP_EOL;
if($pos >= 1536 && $pos <= 1791) {
$arabic_count++;
} else if($pos > 123 && $pos < 123) {
$latin_count++;
}
$total_count++;
}
if(($arabic_count/$total_count) > 0.6) {
// 60% arabic chars, its probably arabic
return true;
}
return false;
}
$arabic = is_arabic('عربية إخبارية تعمل على مدار اليوم. يمكنك مشاهدة بث القناة من خلال الموقع');
var_dump($arabic);
?>
They also show a preg_match statement
$str = "بسم الله";
if (preg_match('/[أ-ي]/ui', $str)) {
echo "A match was found.";
} else {
echo "A match was not found.";
}
You could use the unicode property \p{Arabic}, see http://perldoc.perl.org/perluniprops.html
Using php:
preg_match('/^\p{Arabic}+$/u', $string, $matches);

Resources