How to capture and put regex results to database? - php

$d5 = preg_grep("/(#[0-9]{1,11})/", $d);
in the code above:
$d is a $_POST method textarea input.
I have a preg_grep to find and capture numbers following an # symbol like this: #1234567890
I want to INSERT the $d5 results to a table in the database, but since the preg_grep should return an array I can't put them in as it is. So I tried to use the following method
$d5string = implode(", ", $d5);
but obviously I couldn't address the $d5 results appropriately.
How can I convert this $d5 results to string so I can INSERT the results to a row under related column?
EDIT/UPDATE:
I wrote the below function and realized that I was giving a string to the preg_grep which takes an array. So my question was not logical. I'd like to update my question: How to capture and put regex results to database?
function activeMention($string) {
$find = '/#([0-9]{1,11})/';
return preg_grep($find, $string);
}
I replaced preg_grep() with preg_match_all() in the function. Now the error is gone and var_dump shows int(0)
on variable $d5 = activeMention($string); I put a $_POST['textarea_name'] value as $string
NOW:
The function looks like this:
function activeMention($string) {
$find = '/#([0-9]{1,11})/';
return preg_match_all($find, $string, $matches);
implode(', ', $matches);
}
When I try to insert the variable below to the database I get only the count of captured strings:
$d5 = activeMention($_POST['textarea_name']);
What I actually needed was the array values in 1 string like "#123123, #1234567, #12345"

To get more than one match from a regular expression, you could use preg_match_all like this:
// Define string
$d = 'Here goes one #1234567890 and a #987654321';
// Run regular expression and put matches into $d5 (array with arrays)
$found = preg_match_all("/(#[0-9]{1,11})/", $d, $d5);
// Iterate result
foreach ($d5[0] as $number) {
echo $number, PHP_EOL; // ... or insert into database
}
Output:
#1234567890
#987654321

Here's finally how I did it:
I got rid of the function and used preg_match_all like this:
preg_match_all('/#([0-9]{1,11})/', $_POST['textarea_name'], $out);
$d5s = implode(', ', $out[0]);
and added $d5s to the VALUES in the query to insert into database.

Related

Trying to get lowest value before comma from string using explode

I am new to php but learning fast. I am trying to extract the lowest price from a string of values like -
"12/6/2020:Some Text:345.44,13/6/2020:Some Text:375.88,14/6/2020:Some Text:275.81"
I need to get the value just before each comma and then get the lowest of these values. I know I can use min() if I get these values in a string. For the above example I need 275.81 (lowest).
Please see my code below. I am trying to explode the values and then put in a string. I dont think this is the best way by far and not having any luck. is there a better/cleaner way to do this?
$dates = explode(',', $resultx);
foreach($dates as $datew) {
$dater = explode(':', $datew);
echo $dater[2]. ",";
}
You can use regular expressions to extract the values, and then use min() to get the minimum value
<?php
$input = "2/6/2020:Some Text:345.44,13/6/2020:Some Text:375.88,14/6/2020:Some Text:275.81";
$pattern = '/(?:[^\:]+)\:(?:[^\:]+)\:(\d+\.\d+)\,*/';
if (preg_match_all($pattern, $input, $matches)) {
$minimumValue = min($matches[1]);
echo "minimum is: " . $minimumValue;
}
Here is a working example on 3v4l.org
In the pattern (?:[^\:]+) - equals any symbol, except the colon :
Section (\d+\.\d+) says that we need to capture the sequence containing two numbers with a dot . between them.
We look for two sections with any symbols, except :, and then capturing the third sections containing numbers, and everything ends with an optional comma ,
P.S. you could still get the result with your current approach
<?php
$input = "2/6/2020:Some Text:345.44,13/6/2020:Some Text:375.88,14/6/2020:Some Text:275.81";
$minimumValue = null;
$dates = explode(',', $input);
foreach($dates as $datew) {
$dater = explode(':', $datew);
$currentValue = floatval($dater[2]);
if (is_null($minimumValue) || $minimumValue > $currentValue) {
$minimumValue = $currentValue;
}
}
echo $minimumValue;
Here is a link to your approach on 3v4l.org

PHP match and replace whole word

Hi I am replacing certain names with different value . Here is values I am replacing "#size-name" and "#size" .But the problem is my code replacing only size first and note name for example
#size = "replaceword"
#size-name = "replaceword2"
But its replacing
#size ="replaceword"
#size-name = "replaceword2-name"
How can I replace whole word not part of it here is my code
$tempOutQuery = preg_replace("/(\b($key)\b)/i" , $value , $tempOutQuery);
$tempOutQuery= str_replace("#".$key ,$value ,$tempOutQuery);
both codes are not working
My Full Code
$val= "Hi I want #size dress which is #size-name";
$tempOutQuery = preg_replace("/(\b(size)\b)/i" ,"replaceword", $tempOutQuery);
$tempOutQuery = preg_replace("/(\b(size-name)\b)/i" ,"replaceword2", $tempOutQuery);
If you could make replace without using regulat expressions, then I would suggest using standart str_replace() with arrays:
$val= "Hi i want #size dress which is #size-name";
$search = array('size-name', 'size');
$replace = array('replaceword2', 'replaceword');
$result = str_replace($search, $replace, $val);
The order of search and replace Strings is important!
You should take care that you replace long search-strings first, and the short strings later.
Here's another option for you, using preg_replace_callback. It's actually very similar to Gennadiy's method. The only real difference is that it's using the preg aspect of PHP (and it's a lot more work). But it's another way to skin the proverbial cat.
<?php
// SET OUR DEFAULT STRING
$string = 'Hi I want #size suit which is #size-name';
// LOOK FOR EITHER size-name OR size AND IF YOU FIND IT ...
// RUN THE FUNCTION 'replace_sizes'
$string = preg_replace_callback('~#(size-name|size)~', 'replace_sizes', $string);
// PRINT OUT OUR MODIFIED STRING
print $string;
// THIS IS THE FUNCTION THAT WILL BE RUN EVERY TIME A MATCH IS FOUND
// EITHER 'size' OR 'size-name' WILL BE STORED IN $m[1]
function replace_sizes($m) {
// SET UP AN ARRAY THAT HAS OUR POTENTIAL MATCHES AS KEYS
// AND THE TEXT WE WANT TO REPLACE WITH AS THE VALUE
$size_text_array = array('size-name' => 'replaceword2', 'size' => 'replaceword');
// RETURN WHATEVER THE VALUE IS BASED ON THE KEY
return $size_text_array[$m[1]];
}
This will print out:
Hi I want replaceword suit which is replaceword2
Here is a working demo:
http://ideone.com/njNTbB
You can try pre_replace() to replace whole word from an item of an array in PHP a shown below.
<?PHP
function removePrepositions($text){
$propositions=array('/\bfor\b/i','/\band\b/i');
if( count($propositions) > 0 ) {
foreach($propositions as $exceptionPhrase) {
$text = preg_replace($exceptionPhrase, '', trim($text));
}
$retval = trim($text);
}
return $retval;
}
?>
See the entire post here

Check if URL contains string then create variables with url strings

I need to check if URL contains the term: "cidades".
For example:
http://localhost/site/cidades/sp/sorocaba
So, if positive, then I need to create two or three variables with the remaining content without the " / ", in this case:
$var1 = "sp";
$var2 = "sorocaba";
These variables will be cookies values in the beggining of the page, then, some sections will use as wp-query these values to filter.
This should work for you:
Here I check with preg_match() if the search word is in the url $str between two slashes. If yes I get the substr() from the url after the search word and explode() it into an array with a slash as delimiter. Then you can simply loop through the array an create the variables with complex (curly) syntax.
<?php
$str = "http://localhost/site/cidades/sp/sorocaba";
$search = "cidades";
if(preg_match("~/$search/~", $str, $m, PREG_OFFSET_CAPTURE)) {
$arr = explode("/", substr($str, $m[0][1]+strlen($m[0][0])));
foreach($arr as $k => $v)
${"var" . ($k+1)} = $v;
}
echo $var1 . "<br>";
echo $var2;
?>
output:
sp
sorocaba
Here are two functions that will do it for you:
function afterLast($haystack, $needle) {
return substr($haystack, strrpos($haystack, $needle)+strlen($needle));
}
And PHP's native explode.
First call afterLast, passing the /cidades/ string (or just cidades if you don't expect the slashes). Then take the result and explode on / to get your resulting array.
It would look like:
$remaining_string = afterLast('/cidades/', $url);
$items = explode('/', $remaining_string)
Just note that if you do not include the / marks with the afterLast call, your first element in the explode array will be empty.
I think this solution is better, since the resulting array will support any number of values, not just two.

In comma delimited string is it possible to say "exists" in php

In a comma delimited string, in php, as such: "1,2,3,4,4,4,5" is it possible to say:
if(!/*4 is in string bla*/){
// add it via the .=
}else{
// do something
}
In arrays you can do in_array(); but this isn't a set of arrays and I don't want to have to convert it to an array ....
Try exploding it into an array before searching:
$str = "1,2,3,4,4,4,5";
$exploded = explode(",", $str);
if(in_array($number, $exploded)){
echo 'In array!';
}
You can also replace numbers and modify the array before "sticking it back together" with implode:
$strAgain = implode(",", $exploded);
You could do this with regex:
$re = '/(^|,)' + preg_quote($your_number) + '(,|$)/';
if(preg_match($re, $your_string)) {
// ...
}
But that's not exactly the clearest of code; someone else (or even yourself, months later) who had to maintain the code would probably not appreciate having something that's hard to follow. Having it actually be an array would be clearer and more maintainable:
$values = explode(',', $your_string);
if(in_array((str)$number, $values)) {
// ...
}
If you need to turn the array into a string again, you can always use implode():
$new_string = implode(',', $values);

Splitting a string to put into a CodeIgniter Active Record SQL query

I am trying to do a search query to see if a textarea contains some keywords. I'm having a bit of trouble though plugging my textarea's values into the query.
This is my query:
$match = $this->input->post('wStory');
$this->db->where("`terms` LIKE '%$match%'");
$query = $this->db->get('filter_tbl');
return $query->num_rows();
The $match is my text field and what I have been trying to do is split up the words inside and then run through each individual word. I have tried using PHPs' explode() function which sort of works, but in this case it doesn't work because it turns the string into an array.
Is there any way I can split up the strings in my textarea to just words and run through the words in the like statement, Or is there just something I'm missing?
The query you're currently running is doing a check for a specific phrase, rather than checking for any of the specified words.
You need to do the following:
$match = $this->input->post('wStory');
// break search phrase into keywords
$keywords = explode(' ', $match);
// Build query
foreach ($keywords as $keyword)
{
$keyword = trim($keyword);
$this->db->or_where("`terms` LIKE '%$keyword%'");
}
$query = $this->db->get('filter_tbl');
return $query->num_rows();
The explode(' ', $match) does not take into account any punctuation that might separate words.
Isn't there a $this->db->like("terms", $match); method?
See http://ellislab.com/codeigniter/user-guide/database/active_record.html#like
I think fulltext search is the way to go. The url Rob W posted also gives this:
$this->db->where('MATCH (field) AGAINST ("value")', NULL, FALSE);
which in you care would be something like
$this->db->where('MATCH (terms) AGAINST ("$match")', NULL, FALSE);
Edit: After reading some further, this might be better (or atleast better readable):
$this->db->where('MATCH (terms) AGAINST ("$match")');
Try this:
$match = $this->input->post('wStory');
//Getting words from textarea and put them into array
$wordsArray = explode(' ',$match);
if (!empty($wordsArray)) {
//use where_in() instead of where()
$this->db->where_in("`terms`", $wordsArray);
$query = $this->db->get('filter_tbl');
return $query->num_rows();
}

Categories