Adding character at the beginning and end of a list of items [closed]
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
开发者_如何学编程Closed 8 years ago.
Improve this questionI have long a txt file list like this
dddd
ggggb
btbtgbgb
gtrbr
and I want each item to be like this:
'dddd'
'ggggb'
'btbtgbgb'
'gtrbr'
echo "'" . str_replace(' ', "' '", 'dddd ggggb btbtgbgb gtrbr') . "'";
// returns 'dddd' 'ggggb' 'btbtgbgb' 'gtrbr'
$str = "dddd ggggb btbtgbgb gtrbr";
echo "'" . str_replace(' ', "' '", preg_replace('/\s\s+/', ' ', $str)) . "'";
//returns 'dddd' 'ggggb' 'btbtgbgb' 'gtrbr' and strips extra whitespace if ever your text file has extra whitespaces.
// load file into an array
$lines = file($textfile);
foreach ($lines as $key => $line) {
// add quotes and remove tailing newline
$lines[$key] = "'".rtrim($line, "\n")."'";
}
print_r($lines);
Note: This will probably not scale very well.
精彩评论