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
Related
My problem is it just replicates the number twice, though it does add the break when there is a number, but I'm trying to check if there is a number after the number, so it would say line 12 is.....
Thanks for any help
<?PHP
$lines = file_get_contents('http://www.webstitcher.com/test.txt');
$tag = str_split($lines); // puts all lines into a array
foreach ($tag as $num => $letta){
if (is_numeric($letta) == TRUE){
$num2 = $num++;
if (is_numeric($tag[$num2])){ // checks if next line is going to be another digit
$letta .= $tag[$num2];
unset($tag[$num2]); // removes line if it had another digit and adds to ouput
}
echo '<br />' . $letta;
}
else {
echo $letta;
}
}
?>
Try exploding the string using ' ' as the delimiter. This will allow you to keep the numbers whole and will ultimately help cut out a lot of the complexity.
$lines = file_get_contents('http://www.webstitcher.com/test.txt');
$tag = explode(' ', $lines); // puts all words into a array
foreach ($tag as $word){
if (is_numeric($word)) {
// if the word is numeric, simply skip to next line
// if you need to keep the number, add $word to the echo statement
echo '<br />';
}
else {
echo ' '.$word;
}
}
This way you don't have to keep track of the previous element in the array or check for the next element.
Alternatively, you could also use preg_replace which would remove the need for the loop entirely.
$lines = preg_replace('/[0-9]+/', '<br>', $words);
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']);
I have a php value coming back from my database as a string, like
"this, that, another, another"
And I'm trying to wrap a separate link around each of those strings, but I can't seem to get it to work. I've tried a for loop, but since it's just a string of information and not an array of information that doesn't really work. Is there a way to wrap a unique link around each value in my string?
The easiest way that I see to do this would be using PHP's explode() function. You'll find that it will become very useful as you start to use PHP more and more, so do check out its documentation page. It allows you to split a string up into an array given a certain separator. In your case, this would be ,. So to split the string:
$string = 'this, that, another, another 2';
$parts = explode(', ', $string);
Then use a foreach (again, check the documentation) to iterate through each of the parts and make them into a link:
foreach($parts as $part) {
echo '' . $part . "\n";
}
However, you can do this with a for loop. Strings can be accessed like arrays, so you can implement a parser pattern to parse the string, extract the parts, and create the links.
// Initialize some vars that we'll need
$str = "this, that, another, another";
$output = ""; // final output
$buffer = ""; // buffer to hold current part
// Iterate over each character
for($i = 0; $i < strlen($str); $i++) {
// If the character is our separator
if($str[$i] === ',') {
// We've reached the end of this part, so add it to our output
$output .= '' . trim($buffer) . "\n";
// clear it so we can start storing the next part
$buffer = "";
// and skip to the next character
continue;
}
// Otherwise, add the character to the buffer for the current part
$buffer .= $str[$i];
}
echo $output;
(Codepad Demo)
A better way is to do it like this
$string = "this, that, another, another";
$ex_string = explode(",",$string);
foreach($ex_string AS $item)
{
echo "<a href='#'>".$item."</a><br />";
}
First explode the string to get the individual words in an array. Then add the hyperlinks to the words and finally implode them.
$string = "this, that, another, another";
$words = explode(",", $string);
$words[0] = $words[0]
$words[1] = $words[1]
..
$string = implode(",", $words);
You can also use the for loop to assign hyperlinks that follow a pattern like this:
for ($i=0; $i<count($words); $i++) {
//assign URL for each word as its name or index
}
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'm using a CSV script from phpclasses.org. It retrieves column names and column values from a table/more tables and creates a CSV.
There's one thing I don't understand.
Here's the piece of code I'm looking at:
function createcsv($tablename){
$rs = $this->SelectAll($tablename);
$rs1 = $this->SelectAll($tablename);
if($rs){
$string ="";
/// Get the field names
$fields = mysql_fetch_assoc($rs1);
if(!is_array($fields))
return;
while(list($key,$val) =each($fields)) {
$string .= $key.',';
}
$string = substr($string,0,-1)."\015\012"; //removes last and comma and adds a newline
/// Get the data
while($row = mysql_fetch_assoc($rs)) {
while(list($key,$val) =each($row)){
$row[$key] = strip_tags(html_entity_decode($row[$key])); //strips tangs from the html decoded value
$row[$key] = str_replace(',',' ',rtrim($row[$key])); //replaces commas with empty spaces from the trimmed value
$row[$key] = str_replace("\015\012",' ',$row[$key]);
}
$string .= (implode($row,","))."\015\012";
}
echo $string;
//$fp = fopen($this->path.$tablename.".csv",'w');
//fwrite($fp,$string);
//fclose($fp);
}
}
The 2 lines I'm wondering about are:
$row[$key] = str_replace(',',' ',rtrim($row[$key])); //replaces commas with empty spaces from the trimmed value
$row[$key] = str_replace("\015\012",' ',$row[$key]);
I thought rtrim removes new lines too (\n)... so why is the second line $row[$key] = str_replace("\015\012",' ',$row[$key]); used?
rtrim removes newlines from the end (r = "right") of the string. The line you quoted removes them anywhere in the string.
Looking at the page you kindly linked in your question, I can read
from the end of a string
so, I can conclude that it doesn't remove any new lines from whatever else part of the string.