0

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|[email protected]|123-456-7890

2
  • 2
    str_replace('|', ': <br />', 'Name|Address|Email|Phone')? Commented Mar 15, 2020 at 11:20
  • Name|Address|Email|Phone is the format not the data in itself. The data would look something like Foo Bar|123, Foo Lane|[email protected]|123-456-7890 Commented Mar 15, 2020 at 11:22

3 Answers 3

1

I presume something like this should help:

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

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

Fiddle here.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Did exactly what I required and is pretty much elegant. I'll just tweak it to work my entire file.
0

You can use

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

Comments

0

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.

<?php
function get_line() {
    $data =<<<DATA
Holmes|Baker Street|[email protected]|01234 56789
Mouse|Baker Street|[email protected]|01234 67890
DATA;

    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 />';
}

Output:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.