php String from user input and from database - php

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);

Related

How to Explode the string in Codeigniter

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 ,

Manipulating Strings in PHP with Functions

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.

Declaring variable inside string

I have this kind of string.
'"asdfasdf","123456", this is a message. OK'
What i want to do is declare variables according to the first, second quotation and the rest of the message until the OK...
(note: the length of the string inside the '' is not consistent)
$First = "asdfasdf"
$Second = "123456"
$Message = "this is a message"
is this even possible?
is there something like " "$First","$Second", "$Message" OK " kind of way?
TIA.
Is this a CSV file ?
Doesn't seem to, but if it was you should check out the csv functions of php, specifically str_getcsv.
If not, you should just do an explode by , or ", or any combination you think would be most accurate, and then go through each array item.
$string = '"asdfasdf","123456","this is a message. OK"';
$temp = explode('","',$string);
$array = array();
foreach($temp as $key=>$value){
//do stuff with $value and $key
}
You can use regular expressions, like this:
Code
$raw = '"asdfasdf","123456", this is a message. OK'; // this is your raw text
preg_match('/^"(?P<first>[^"]+)","(?P<second>[^"]+)",\s+(?P<message>.+?) OK/', $raw, $matches); // this looks for the pattern you defined and stores the matches in $matches
print_r($matches); // this just dumps out the array of matching substrings
Output
Array
(
[0] => "asdfasdf","123456", this is a message. OK
[first] => asdfasdf
[1] => asdfasdf
[second] => 123456
[2] => 123456
[message] => this is a message.
[3] => this is a message.
)
You can access the individual substrings as, for example, $matches['first'], $matches['second'], or $matches['message'].
PHP Demo
Regex Demo

how to parse $_REQUEST?

here i am checking for and getting part of the request, (the ids). i also print out the entire request:
if (isset($_REQUEST['ids'])){
$amount = sizeof($_REQUEST['ids']);
print_r($_REQUEST);
echo "<br>$amount invitations Successfully Sent";
}
this is how the entire $_REQUEST prints out:
Array
(
[mfs_typeahead_req_form_4cf74f96db3688507476560] => Start Typing a Name
[ids] => Array
(
[0] => 510149460
)
[fbs_258181898823] => \"access_token=258181898823|2.q_qb_yoReO0_xc4H8PxKRQ__.3600.1291280400-100000664203700|LqtGr_OiJTASGmek61awxmxfvFk&expires=1291280400&secret=85eTEELZj8lkV82V_PwRSA__&session_key=2.q_qb_yoReO0_xc4H8PxKRQ__.3600.1291280400-100000664203700&sig=d4cc0e4c0992ea29c0adfd60dc27185b&uid=100000664203700\"
)
i need to parse the part at the end: &uid=100000664203700, specifically '100000664203700'
$queryString = $_REQUEST["fbs_258181898823"];
$output = array();
parse_str($queryString, $output);
print $output["uid"];
parse_str() will break up things that look like a query string. I recommend you pass an array as the second parameter.
You can use parse_str()—it should do the trick.
First, remove the \" (using a combination of preg_replace and stripslashes) at the beginning and the end, then use parse_str:
$str = preg_replace('/(^"|"$)/', '', stripslashes($_REQUEST['fbs_258181898823']));
parse_str($str, $data);
$uid = $data['uid'];

declare or convert a string to array format PHP

How to convert a string format into an array format?
I have a string, $string = 'abcde'
I want to convert it to a 1 element array
$string[0] = 'abcde'
Is there a built in function for this task? Or the shortest way is to
$string = 'abcde';
$array[0] = $string;
$string = $array;
TIA
All kinds of ways in php..
$array = array('abcde');
$array[] = 'abcde';
Etc... not too sure what you're going for.
Edit: Oh, I think you might want to convert the first variable? Like this?
//Define the string
$myString = 'abcde';
//Convert the same variable to an array
$myString = array($myString);
Edit 2: Ahh, your comment above I think clears it up a little. You're getting back either an array or a string and don't know which. If you do what I just said above, you might get an array inside an array and you don't want that. So cast instead:
$someReturnValue = "a string";
$someReturnValue = (array)$someReturnValue;
print_r($someReturnValue);
//returns
Array
(
[0] => a string
)
$someReturnValue = array("a string inside an array");
$someReturnValue = (array)$someReturnValue;
print_r($someReturnValue);
//returns
Array
(
[0] => a string inside an array
)
Lets not forget the standard way of declaring a string as an array in PHP, before adding elements..
$string = array();

Categories