I'm attempting to concatenate two values from a serialized array. I have this working well. The problem is one of the values Size in this case, contains white-space. I need to remove this whitespace. I have used preg_match before to remove the white-space from a variable/string. The problem I have here is how I might implement preg_match in this instance, if it is the correct approach.
foreach($contents as $item)
{
$save = array();
$item = unserialize($item);
**$item['sku'] = $item['sku'] . '' . $item['options']['Size'];**
//echo '<pre>';
//print_r($item['sku']);
//exit();
$save['contents'] = serialize($item);
$save['product_id'] = $item['id'];
$save['quantity'] = $item['quantity'];
$save['order_id'] = $id;
$this->db->insert('order_items', $save);
}
Many thanks.
PHP has function named trim() that allows trimming strings.
You can simply use str_replace like this:
$item['sku'] .= ' ' . str_replace(' ', '', $item['options']['Size']);
Related
Im trying to filter some entry's in a While loop. This i'm trying to do with the strpos function, unfortunately when i use a variable as needle, i do not get an result.
No result:
$tra = strpos($HRreq, $entry_type)
result: $tra = strpos($HRreq, "string");
But, i need it to be variable in the while loop.
$select_exec = odbc_exec($amos_db,$select_personnel);
while ($row = odbc_fetch_array($select_exec)){
$username = $row['user_sign'];
$entry_type = $row['entry_type'];
$fullname1 = $row['lastname'] . $row['firstname'];
$fullname = trim(preg_replace('/ +/', ' ', preg_replace('/[^A-Za-z0-9 ]/', ' ', urldecode(html_entity_decode(strip_tags($fullname1))))));
$userno = $row['employee_no_i'];
$tra = strpos($HRreq, "$entry_type");
echo $entry_type ." = ". $tra;
}
I've added part of the code since the code is more than 500 lines long. I hope this is enough to get an idea of what i'm trying to accomplish
I discovered that the database returned with white spaces after the variable. I added a trim() and the problem was solved. It was a silly mistake.
I would I am using PHP. I am reading from a file but I would like to eliminate the following characters from the file wherever they are: '' and { }.
I tried to use the trim function but the characters "',{ and }" are still present in the output:
$txt_file = file_get_contents('out.txt');
$rows = explode(",", $txt_file);
array_shift($rows);
foreach($rows as $row => $data)
{
//get row data
$row_data = explode(':', $data);
trim($row,"'");
trim($row,"{");
trim($row,"}");
$info[$row]['state'] = $row_data[0];
$info[$row]['action'] = $row_data[1];
echo $info[$row]['state'] . '<br />';
echo $info[$row]['action'] . '<br />';
echo '<br />';
}
Do you have any idea how to do it?
Thanks
I assume you want to remove ' { and } from $row
If it is, then replace
trim($row,"'");
trim($row,"{");
trim($row,"}");
with
$row = str_replace(['\'', '{', '}'], '', $row);
Note: trim — Strip whitespace (or other characters) from the beginning and end of a string. Moreover you didn't store trimmed data to any variable so literally you will not get trimmed data. You want to replace characters wherever it is found so use str_replace or preg_replace. Please check PHP manual for more details
This question already has answers here:
PHP: How can I explode a string by commas, but not wheres the commas are within quotes?
(2 answers)
Closed 8 years ago.
I'm trying to figure out how to add double quote between text which separates by a comma.
e.g. I have a string
$string = "starbucks, KFC, McDonalds";
I would like to convert it to
$string = '"starbucks", "KFC", "McDonalds"';
by passing $string to a function. Thanks!
EDIT: For some people who don't get it...
I ran this code
$result = mysql_query('SELECT * FROM test WHERE id= 1');
$result = mysql_fetch_array($result);
echo ' $result['testing']';
This returns the strings I mentioned above...
Firstly, make your string a proper string as what you've supplied isn't. (pointed out by that cutey Fred -ii-).
$string = 'starbucks, KFC, McDonalds';
$parts = explode(', ', $string);
As you can see the explode sets an array $parts with each name option. And the below foreach loops and adds your " around the names.
$d = array();
foreach ($parts as $name) {
$d[] = '"' . $name . '"';
}
$d Returns:
"starbucks", "KFC", "McDonalds"
probably not the quickest way of doing it, but does do as you requested.
As this.lau_ pointed out, its most definitely a duplicate.
And if you want a simple option, go with felipsmartins answer :-)
It should work like a charm:
$parts = split(', ', 'starbucks, KFC, McDonalds');
echo('"' . join('", "', $parts) . '"');
Note: As it has noticed in the comments (thanks, nodeffect), "split" function has been DEPRECATED as of PHP 5.3.0. Use "explode", instead.
Here is the basic function, without any checks (i.e. $arr should be an array in array_map and implode functions, $str should be a string, not an array in explode function):
function get_quoted_string($str) {
// Here you will get an array of words delimited by comma with space
$arr = explode (', ', $str);
// Wrapping each array element with quotes
$arr = array_map(function($x){ return '"'.$x.'"'; }, $arr);
// Returning string delimited by comma with space
return implode(', ', $arr);
}
Came in my mind a really nasty way to do it. explode() on comma, foreach value, value = '"' . $value . '"';, then run implode(), if you need it as a single value.
And you're sure that's not an array? Because that's weird.
But here's a way to do it, I suppose...
$string = "starbucks, KFC, McDonalds";
// Use str_replace to replace each comma with a comma surrounded by double-quotes.
// And then shove a double-quote on the beginning and end
// Remember to escape your double quotes...
$newstring = "\"".str_replace(", ", "\",\"", $string)."\"";
I am having a problem trying to understand functions with variables. Here is my code. I am trying to create friendly urls for a site that reports scams. I created a DB full of bad words to remove from the url if it is preset. If the name in the url contains a link I would like it to look like this: example.com-scam.php or html (whichever is better). However, right now it strips the (.) and it looks like this examplecom. How can I fix this to leave the (.) and add a -scam.php or -scam.html to the end?
functions/seourls.php
/* takes the input, scrubs bad characters */
function generate_seo_link($link, $replace = '-', $remove_words = true, $words_array = array()) {
//make it lowercase, remove punctuation, remove multiple/leading/ending spaces
$return = trim(ereg_replace(' +', ' ', preg_replace('/[^a-zA-Z0-9\s]/', '', strtolower($link))));
//remove words, if not helpful to seo
//i like my defaults list in remove_words(), so I wont pass that array
if($remove_words) { $return = remove_words($return, $replace, $words_array); }
//convert the spaces to whatever the user wants
//usually a dash or underscore..
//...then return the value.
return str_replace(' ', $replace, $return);
}
/* takes an input, scrubs unnecessary words */
function remove_words($link,$replace,$words_array = array(),$unique_words = true)
{
//separate all words based on spaces
$input_array = explode(' ',$link);
//create the return array
$return = array();
//loops through words, remove bad words, keep good ones
foreach($input_array as $word)
{
//if it's a word we should add...
if(!in_array($word,$words_array) && ($unique_words ? !in_array($word,$return) : true))
{
$return[] = $word;
}
}
//return good words separated by dashes
return implode($replace,$return);
}
This is my test.php file:
require_once "dbConnection.php";
$query = "select * from bad_words";
$result = mysql_query($query);
while ($record = mysql_fetch_assoc($result))
{
$words_array[] = $record['word'];
}
$sql = "SELECT * FROM reported_scams WHERE id=".$_GET['id'];
$rs_result = mysql_query($sql);
while ($row = mysql_fetch_array($rs_result)) {
$link = $row['business'];
}
require_once "functions/seourls.php";
echo generate_seo_link($link, '-', true, $words_array);
Any help understanding this would be greatly appreciated :) Also, why am I having to echo the function?
Your first real line of code has the comment:
//make it lowercase, remove punctuation, remove multiple/leading/ending spaces
Periods are punctuation, so they're being removed. Add . to the accepted character set if you want to make an exception.
Alter your regular expression (second line) to allow full stops:
$return = trim(ereg_replace(' +', ' ', preg_replace('/[^a-zA-Z0-9\.\s]/', '', strtolower($link))));
The reason your code needs to be echoed is because you are returning a variable in the function. You can change return in the function to echo/print if you want to print it out as soon as you call the function.
I want to strip the tags off the value inside array_values() before imploding with tabs.
I tried with this line below but I have an error,
$output = implode("\t",strip_tags(array_keys($item)));
ideally I want to strip off the line breaks, double spaces, tabs from the value,
$output = implode("\t",preg_replace(array("/\t/", "/\s{2,}/", "/\n/"), array("", " ", " "), strip_tags(array_keys($item))));
but I think my method is not correct!
this is the entire function,
function process_data($items){
# set the variable
$output = null;
# check if the data is an items and is not empty
if (is_array($items) && !empty($items))
{
# start the row at 0
$row = 0;
# loop the items
foreach($items as $item)
{
if (is_array($item) && !empty($item))
{
if ($row == 0)
{
# write the column headers
$output = implode("\t",array_keys($item));
$output .= "\n";
}
# create a line of values for this row...
$output .= implode("\t",array_values($item));
$output .= "\n";
# increment the row so we don't create headers all over again
$row++;
}
}
}
# return the result
return $output;
}
Please let me know if you have any ideas how to fix this. Thanks!
strip_tags only works on strings, not on array input. Thus you have to apply it after implode made a string of the input.
$output = strip_tags(
implode("\t",
preg_replace(
array("/\t/", "/\s{2,}/", "/\n/"),
array("", " ", " "),
array_keys($item)
)
)
);
You'll have to test if it gives you the desired results. I don't know what the preg_replace accomplishes.
Otherwise you could use array_map("strip_tags", array_keys($item)) to have the tags removed first (if there are really any significant \t within the tags in the strings.)
(No idea what your big function is about.)
try mapping the arrays to strip_tags and trim.
implode("\t", array_map("trim", array_map("strip_tags", array_keys($item))));
Stripping the tags is easy as this:
$a = array('key'=>'array item<br>');
function fix(&$item, $key)
{
$item = strip_tags($item);
}
array_walk($a, 'fix');
print_r($a);
Of course, you can make whatever modifications you like to $item in the fix function. The change will be stored in the array.
For a multidimensional array use array_walk_recursive($a, 'fix');.
Looks like you just need to use array_map, since strip_tags expects a string, not an array.
$arr = array( "Some\tTabbed\tValue" => '1',
"Some value with double spaces" => '2',
"Some\nvalue\nwith\nnewlines" => '3',
);
$search = array("#\t#", "#\s{2,}#", "#\n#");
$replace = array("", " ", " ");
$output = implode("\t", preg_replace($search, $replace, array_map('strip_tags', array_keys($arr))));
echo $output;