PHP – Replace Same Character With Different Ones in String-ThrowExceptions

Exception or error:

I have a file that contains certain data in Name|Address|Email|Phone format. Each line contains the data in the said format for each customer. How do I implode or str_replace to get the format below?

Name: <br>
Address: <br>
Email: <br>
Phone: <br>

I have the idea and thought mapped out but I can’t seem to be able to implement it.

N:B – Name|Address|Email|Phone is the format not the data in itself. The data would look something like Foo Bar|123, Foo Lane||123-456-7890

How to solve:

I presume something like this should help:

$data = explode('|', 'Foo Bar|123, Foo Lane||123-456-7890');
$keys = ['Name', 'Address' ,'Email', 'Phone'];

$result = [];
foreach ($data as $k => $v) {
    $result[] = $keys[$k] . ': ' . $v;
echo implode('<br />', $result);

Fiddle here.


You can use

$lineBreak = "<br/>";
while ($line = fgets($fh)) {
 echo $line = str_replace('|', ":".$lineBreak, $line);


Just use str_getcsv and swap your delimiter for the pipe.

The first part can be swapped out. Just iterate a line/row at a time.

function get_line() {
    $data =<<<DATA
Holmes|Baker Street||01234 56789
Mouse|Baker Street||01234 67890

    foreach(explode("\n", $data) as $line)
        yield $line;

foreach(get_line() as $line) {
    list($name, $address, $email, $phone) = str_getcsv($line, '|');
    echo 'Name: '    . $name    . '<br />';
    echo 'Address: ' . $address . '<br />';
    echo 'Email: '   . $email   . '<br />';
    echo 'Phone: '   . $phone   . '<br />';


Name: Holmes<br />Address: Baker Street<br />Email:<br />Phone: 01234 56789<br />Name: Mouse<br />Address: Baker Street<br />Email:<br />Phone: 01234 67890<br />

Leave a Reply

Your email address will not be published. Required fields are marked *