daffodil
daffodil

Reputation: 197

str_replace specific char with new line

I have a bunch of file. I need to print out the file only ITEM_DESCRIPTION: part. Lets say the contents of each files is like below

// ITEM_DESCRIPTION: Phone 1
//                   - Android 9.0 (Pie)
//                   - 64/128 GB
//                   - Li-Po 3500 mAh

I want the code to display like below

Phone 1
- Android 9.0 (Pie)
- 64/128 GB
- Li-Po 3500 mAh

so far, what I can produce is

// Phone 1 // - Android 9.0 (Pie) // - 64/128 GB // - Li-Po 3500 mAh

How I want to separate the double slash with new line?

Here is my code

// Get file path
// This code inside for loop which i don't write here
$filedir=$filelist[$i];

//Display Item Description
$search       = "ITEM_DESCRIPTION";
$endsearch    = "BRAND";
$contents     = stristr(file_get_contents($filedir), $search);
$description  = substr($contents, 0, stripos($contents, $endsearch));
$rmv_char     = str_replace(str_split('\:'), ' ', $description);
$newline      = str_replace(str_split('\//'), PHP_EOL , $rmv_char);
$phone_dscrpn = substr($newline, strlen($search));

Here is the way I had tried, but it doesn't work

$newline = str_replace(str_split('\//'), PHP_EOL , $rmv_char);
$newline = str_replace(str_split('\//'), "\r\n" , $rmv_char);

Upvotes: 2

Views: 52

Answers (2)

Michael
Michael

Reputation: 2631

Assuming that all of your lines begin with // and this pattern isn't used in the actual product description then you can use a simple regular expression:

$description = preg_replace('~//\s(ITEM_DESCRIPTION:)?\s+~', '', $description);
  • Match //\s where \s is any white-space
  • Optionally match ITEM_DESCRIPTION:
  • Match \s+ any number of white-space characters

This will give you:

Phone 1
- Android 9.0 (Pie)
- 64/128 GB
- Li-Po 3500 mAh

Upvotes: 1

lufc
lufc

Reputation: 2040

It looks like you already have newlines in the original data so you don't need to add them again. You just need to clear the slashes and the spaces (or tabs if that's what they are, hard to tell on SO).

Remember if you're testing output in browser it won't show the newlines without <pre></pre>.

// Get file path
// This code inside for loop which i don't write here
$filedir=$filelist[$i];

//Display Item Description
$search       = "ITEM_DESCRIPTION";
$endsearch    = "BRAND";
$contents     = stristr(file_get_contents($filedir), $search);
$description  = substr($contents, 0, stripos($contents, $endsearch));

//Clear out the slashes
$phone_dscrpn = str_replace("//", "", $description);

//Clear out the spaces
while(strpos($phone_dscrpn,"  ")!==false) {
    $phone_dscrpn = str_replace("  ", " ", $phone_dscrpn);
}

Note this will replace any double slashes or double spaces within the description. If this could be an issue then you will need to consider a more advanced approach (e.g. line by line).

Upvotes: 2

Related Questions