Reputation: 417
At first take a look to my script:
<?php
$list=file_get_contents('txt.txt');
$name=explode('\r\n',$list); //file exploding by \n because list is one under one
foreach($name as $i1){
echo ($i1);
echo '</br>';
}
?>
it is showing my result (according to list) :
morgan daniel martin sopie tommy
But I have used </br>
so that it must be showing :
morgan
daniel
martin
sopie
tommy
But maybe I am missing something.
Upvotes: 1
Views: 2832
Reputation: 21
Not exactly answering the question but I was trying to use explode('\<br\>',$string)
on a string that I had already run nl2br($string)
on, so I could use the <br>
page breaks as a delimiter and it wasn't working.
The nl2br
actually inserts <br />
values (which Muthu mentioned as the correct format), so if you first run nl2br()
then want to use the inserted html page breaks as a delimiter for explode()
, be sure to use explode('<br />',$string)
on your results.
In Google Chrome, when I had done an inspect on the page, the results were showing with <br>
. When I viewed the page source, I saw that they were actually <br />
. Thought this may save someone some time if they run into similar problems.
Upvotes: 0
Reputation: 9300
explode()
splits as per the given boundary string so you have to include all the whitepace charactes.
You can find the execution see online
So better go for regex which can be used with preg_split() with regex pattern "\s" - the whitespace character class
---edited---
//$list = $list = preg_replace('<br>',' ',$list);; // replace the <br> with space
$list = str_replace('<br>',' ',$list); //better than preg_replace as regex dont
// wok better for html tags
---EOF edited---
$name = preg_split('/\s+/',$list);
echo '<pre>';
print_r($name);
echo '</pre>';
-----------o/p---------
Array ( [0] => morgan [1] => daniel [2] => martin [3] => sopie [4] => tommy )
note:
The replace since it's a hardcoded string function.
The Regex will take longer since it needs to parse the regex string (even if you set RegexOptions.Compiled) then execute it in the regex string then formulate the resultant string. But if you really want to be sure, perform each iteration in a million-times iterator and time the result.
Go through this:
Shorthand Character Classes(\s)
Upvotes: 1
Reputation: 2775
In this situation better to use preg_replace
... as you don't understand it well, can use below tricks... see the below code...
<?php
$list=file_get_contents('txt.txt');
echo implode('<br>',explode(' ',$list));
?>
HTML:
morgan<br>daniel<br>martin<br>sopie<br>tommy
Output Preview:
morgan
daniel
martin
sopie
tommy
if you want a break at the end too... use below one...
echo implode('<br>',explode(' ',$list)).'<br>';
Upvotes: 2
Reputation: 12860
Use php file
instead to loop through lines of a doc:
http://www.php.net/manual/en/function.file.php
Upvotes: 1