So i have this in my test.txt file:
5436 : Ball Of Yarn
1849 : Blue Border Collie Headband
24063 : Blue Border Collie Hoodie
I'm trying to remove everything before the ":", this is my PHP code:
$str = file_get_contents("test.txt");
$string2 = substr($str, ($pos = strpos($str, ' : ')) !== false ? $pos + 1 : 0);
file_put_contents("test.txt", $string2);
Help me please
you can do something like this:
$arr = file("test.txt");
foreach ($arr as $line) {
echo substr($line, ($pos = strpos($line, ' : ')) !== false ? $pos + 1 : 0);
}
If you are not afraid to use regex you can use this: (works if your characters before : are numbers only). If you need other chars let me know.
$str = file_get_contents("test.txt");
$string2 = preg_replace('/[0-9 ]+:/', "", $str);
file_put_contents("test.txt", $string2);
This does what you wanted exactly and keeps your structure; just second line is changed :)
See more about regex here or in this basic tutorial which looks nice to start with.
You could try to use fgetcsv
. Here is an example of use :
$ cat test.txt
5436 : Ball Of Yarn
1849 : Blue Border Collie Headband
24063 : Blue Border Collie Hoodie
$ cat test.php
#!/usr/bin/php
<?php
$in_file="test.txt";
if (false !== ($handle = fopen($in_file, "r"))){
while(false !== ($line = fgetcsv($handle, 0, ":"))){
if(isset($line[1]) && $line[1]){
echo "LINE=" . trim($line[1]) . "\n";
}
}
}
?>
$ ./test.php
LINE=Ball Of Yarn
LINE=Blue Border Collie Headband
LINE=Blue Border Collie Hoodie
Another solution using preg_replace
:
$ cat test.php
#!/usr/bin/php
<?php
$in_file="test.txt";
if (false !== ($handle = fopen($in_file, "r"))){
while(false !== ($line = fgets($handle))){
echo "LINE=" . trim(preg_replace("/^[^:]*:\ ?([^:]*)$/", "$1", $line)) . "\n";
}
}
?>
$ ./test.php
LINE=Ball Of Yarn
LINE=Blue Border Collie Headband
LINE=Blue Border Collie Hoodie
Here's a solution using array_map to alter the contents of each line then write to the file, with perhaps a better way of stripping the line for you:
function editLine($line) {
return strstr($line, ':') ?: $line;
}
$lines = file('test.txt');
$editedLines = array_map('editLine', $lines);
file_put_contents('test.txt', implode('', $editedLines));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.