Skip to content
Advertisement

PHP – Replace Same Character With Different Ones in String

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|foo@bar.com|123-456-7890

Advertisement

Answer

I presume something like this should help:

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

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

Fiddle here.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement