I want to explore the following string which I am fetching from the database in CodeIgniter using a foreach loop. Actually, I am using a double delimiter to differentiate tags like SQL and MySQL because LIKE "%sql%" will return MySQL results as well. Should be LIKE "%|sql|%"
|login||background||signup||material-design|
I tried the following code but no success.
$snippettag_id = explode('|', $snippet_tags);
foreach($snippettag_id as $tag_id) {
$tag_name = $tag_id;
$this->db->or_like('snippets_name', $tag_name);
}
Your issue is with same delimiter and symbol in text, Here you need to replace your delimiter in db and in explode(), Try to save , instead of | as delimiter
$str = "|sql|,|Mysql|,|php|,|C#|,|C++|";//DB string
echo'<pre>';echo $str;
$strArray = explode(',', $str);
echo'<pre>';print_r($strArray);die;
Output:
|sql|,|Mysql|,|php|,|C#|,|C++|
Array
(
[0] => |sql|
[1] => |Mysql|
[2] => |php|
[3] => |C#|
[4] => |C++|
)
Apart from solution
you should probably normalize your database it will more reliable and easy to do searching in future
If you need the output as you mentioned above without using , characters so you can still do that easy
First run your query normal without any modification so results will be
$result = "login background signup material";
After that use explode with,
$snid = explode("," , $result);
Now you need | in your result you can do the following
$finalresult = str_ireplace(",", "|", "$snid");
Now output have | instead of ,
Related
My string looks like this 05/21/2018 ghijkl 06/12/2018 mnopqrst
I need to extract all the values after each date and include the date. I tried
explode('/2018', $string);
But that splits up the date and is also not future-proof. I'm thinking there must be a way to include the delimiter in the element. Perhaps there is also a regular expression I should be using to find the date?
Thank you.
You could use preg_split with the PREG_SPLIT_DELIM_CAPTURE and the PREG_SPLIT_NO_EMPTY flags to keep the delimiter and remove the empty values from the resulting array.
You might use a pattern that matches a date format \b\d{1,2}/\d{1,2}/\d{4}\b (Note that it matches your date format in the example data and does not validate a date itself)
For example:
$str = '05/21/2018 ghijkl 06/12/2018 mnopqrst';
$result = preg_split('#(\b\d{1,2}/\d{1,2}/\d{4}\b)#', $str, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
var_dump($result);
Demo
To validate a date you could use DateTime and perhaps specify your format using createFromFormat.
$date = DateTime::createFromFormat("m/d/Y", '05/21/2018');
You can use current(explode('/', $string));
You can do something like this
$str = '05/21/2018 ghijkl 10/12/2017 mnopqrst';
$arr = explode(' ',$str);
$new = array();
for($i=0;$i<count($arr);$i+=2){
$new[] = ["date"=>$arr[$i],"value"=>$arr[$i+1]];
}
print_r($new);
Live Demo
Output:
Array
(
[0] => Array
(
[date] => 05/21/2018
[value] => ghijkl
)
[1] => Array
(
[date] => 10/12/2017
[value] => mnopqrst
)
)
Assuming your date is guaranteed to be formatted as you mentioned (if it's user input data, it's generally not safe to assume that), you could use a regular expression to find strings after a date:
Using a PHP regex split with the below expression:
/([0-9]{1,2}\/[0-9]{1,2}\/[0-9]{2,4})([a-zA-Z\s]+)/g
Will break 05/21/2018 ghijkl 10/12/2017 mnopqrst into an array with the different groups. Depending how you actually want the output data, you can capture the date and subsequent string in one match group.
Sample code:
$string = '05/21/2018 ghijkl 10/12/2017 mnopqrst';
preg_split('/([0-9]{1,2}\/[0-9]{1,2}\/[0-9]{2,4})([a-zA-Z\s]+)/g', $string, $stringParts);
array (
0 => '05/21/2018',
1 => 'ghijkl',
2 => '10/12/2017',
3 => 'mnopqrst'
);
https://regex101.com/r/gPXkDz/2
You could do that using regular expressions. Here's an example code:
<?php
$string = '05/21/2018 ghijkl 06/12/2018 mnopqrst';
$matches = [];
if (preg_match_all('#(\d{2}\/\d{2}\/\d{4})#i', $string, $matches) > 0) {
echo "Found the following dates: \n";
foreach ($matches[0] as $date) {
printf("- %s\n", $date);
}
}
This would result in the following output:
Found the following dates:
- 05/21/2018
- 06/12/2018
I am scraping the following kind of strings from an external resource which I can't change:
["one item",0,0,2,0,1,"800.12"],
["another item",1,3,2,5,1,"1,713.59"],
(etc...)
I use the following code to explode the elements into an array.
<?php
$id = 0;
foreach($lines AS $line) {
$id = 0;
// remove brackets and line end comma's
$found_data[] = str_replace(array('],', '[',']', '"'), array('','','',''), $line);
// add data to array
$results[$id] = explode(',', $line);
}
Which works fine for the first line, but as the second line uses a comma for the thousands seperator of the last item, it fails there. So somehow I need to disable the explode to replace stuff between " characters.
If all values would be surrounded by " characters, I could just use something like
explode('","', $line);
However, unfortunately that's not the case here: some values are surrounded by ", some aren't (not always the same values are). So I'm a bit lost in how I should proceed. Anyone who can point me in the right direction?
You can use json_decode here since your input string appears to be a valid json string.
$str = '["another item",1,3,2,5,1,"1,713.59"]'
$arr = json_decode($str);
You can then access individual indices from resulting array or print the whole array using:
print_r($arr);
Output:
Array
(
[0] => another item
[1] => 1
[2] => 3
[3] => 2
[4] => 5
[5] => 1
[6] => 1,713.59
)
I searched every single str_replace, preg_replace, substr on StackOverflow and can't wrap my head around this.
The strings in my data are as such: "010758-01-700" or "860862-L-714". These are just examples.
These strings are 's
Instance 1:
010758-01-700
/ImageServices/image.ashx?itemid=010758&config=01&format=l&imagenumber=1
If you look carefully at the URL and the string above it, I need to split this as "01075&config=01" and drop "-700" from the string to return a value I can insert into the URL
Instance 2:
860862-L-714
/ImageServices/image.ashx?itemid=870078&color=001&format=l&imagenumber=1
I need to split this as "860862&&color=714" and drop all instances of "-XXS-, -XS-, -S-, -M-, -L-, -XL- ,-XXL-" for the string to return a value I can insert into the URL
There are strings that look like this throughout the data, 860862-L-714, 860862-M-999, 860862-XS-744. These are variations of product with the same name but different
I have tried str_replace("-", "&config=", {ItemNo[1]}) but it returns 010758&config=01&config=700
I'd need to contain this all into a function that I can call into the URL
myFunction({ItemNo[1]})
Then I can setup the URL as so /ImageServices/image.ashx?itemid=
myFunction({ItemNo[1]})&format=l&imagenumber=1
and if my logic is correct, it should work. I'm using WP All Import to import XML data.
How do I create a function that will manipulate the string based on both instances above and output the results I'm trying to achieve?
Ok - based on the responses, I've solved the first instance to get the correct url to display - $content being the ItemNo
<?php
function ItemNoPart1 ( $content ) {
$content1 = explode("-", $content);
return $content1[0];
}
function ItemNoPart2 ( $content ) {
$content2 = explode("-", $content);
return $content2[1];
}
?>
/ImageServices/image.ashx?itemid=[ItemNoPart1({ItemNo[1]})]&config=[ItemNoPart2({ItemNo[1]})]&format=l&imagenumber=1
Now I just need to figure out how to do part 2 and combine it all into 1 function.
Don't use str_replace, use explode instead:
$str = '010758-01-700';
$chunks = explode( '-', $str );
By this way, resulting $chunks is an array like this:
[0] => 010758
[1] => 01
[2] => 700
So, now you can format desired URL in this way:
$url = "/ImageServices/image.ashx?itemid={$chunks[0]}&config={$chunks[1]}&format=l&imagenumber=1"
Your desired function is this:
function myFunction( $itemID )
{
$chunks = explode( '-', $itemID );
return "/ImageServices/image.ashx?itemid={$chunks[0]}&config={$chunks[1]}";
}
... but, really you want a function for this stuff?
Read more about explode()
Here's some psuedo code that may lead you in the right direction. The idea is to build out an array that contains all of the possible pieces of data from our string.
I've used a given constant of /ImageServices/image.ashx? to split upon, as we know the URL of our endpoint.
// explode our string into multiple parts
$parts = explode('/ImageServices/image.ashx?', $str);
// we know that the string we need to parse as at the index of 1
parse_str($parts[1], $parsed);
//$wanted will contain all of the data we can possibly need.
$wanted = array($parts[0], $parsed);
This will yield an array that looks like the following:
array (
0 => '860862-L-714 ',
1 =>
array (
'itemid' => '870078',
'color' => '001',
'format' => 'l',
'imagenumber' => '1',
),
)
Now you can perform your conditionals such as when you need to look for color and create a specific URL structure:
if(array_key_exists('color', $wanted[1]){
//create our custom sting structure here.
}
Hopefully this helps.
I want to extract matched parts of strings --digital part from an array
array("HK00003.Day","HK00005.Day").
<?php
$arr=array("HK00003.Day","HK00005.Day");
$result= array();
foreach ($arr as $item){
preg_match('/[0-9]+/',$item,$match);
array_push($result,$match[0]);
}
It can get the result :00003 00005,it seems tedious,preg_grep seems simple but the result is not what i want .
preg_grep('/[0-9]+/',$arr);
The output is "HK00003.Day","HK00005.Day", not 00003 00005,
is there more simple way to get the job done?
You can use preg_filter (which already uses preg_replace and does not require additional callback functions) to replace the each entry in the array with the number inside:
<?php
$arr = array("HK00003.Day","HK00005.Day");
$matches = preg_filter('/^.*?([0-9]+).*/', '$1',$arr);
print_r($matches);
?>
Output of a sample program:
Array
(
[0] => 00003
[1] => 00005
)
This should work for you:
(Here I just get rid off every character in your array which isn't a number with preg_replace())
<?php
$arr = ["HK00003.Day", "HK00005.Day"];
$result = preg_replace("/[^0-9]/", "", $arr);
print_r($result);
?>
output:
Array ( [0] => 00003 [1] => 00005 )
Your code is fine, not tedious at all. If you want a one-liner you can try something like this (remove everything that's not a digit):
array_push($result, preg_replace("~[^0-9]~", "", $item));
preg_grep return array entries that match the pattern! Therefore, it returns an array of entry rather than the matching string
try below:
preg_match_all('/[0-9]+/',implode('-',$arr),$result);
I have a problem about this strings
currently i save some strings into the database with simple insert query and cleaning the data by this code
mysql_real_escape_string($data)
i get the data from the database using a simple query
sample input
$saveString = "You're great";
saving...
Insert into . . . values (mysql_real_escape_string($saveString))
now when i get the string i get the You're great string
When i use this code
$str = str_word_count(strtolower($fromDbString), 1);
print_r($str);
It outputs:
Array
(
[0] => You're
[1] => great
)
But if the string came from the users input in textbox and i use this code.
$str = str_word_count(strtolower($fromUserInput), 1);
print_r($str);
I get something like this:
Array
(
[0] => You
[1] => re
[2] => great
)
How do i fix the string from the database to be process like the one from the users input?
I tried htmlentities() to check the values and the output was
from db You're great
from input You're great
i tried to html decode the string from db but it still outputs You're great
You could try to add addslashes():
$str = str_word_count(addslashes(strtolower($fromUserInput)), 1);
print_r($str);
If you want to return an array that contains all the string words you could try this instead str_word_count
$str = preg_split("/[' ]/", strtolower($fromUserInput));
//$str = preg_split("/[' ]/", strtolower($fromDbString));
print_r($str);