Home > Software engineering >  PHP str_ireplace for array
PHP str_ireplace for array

Time:10-26

I am trying to remove certain strings from an array of strings

$replace = array(
    're: ', 're:', 're',
    'fw: ', 'fw:', 'fw',
    '[Ticket ID: #'.$ticket["ticketnumber"].'] ',
);

$available_subjects = array($ticket["subject"], $update["subject"]);

I tried using these loops

This replaced words like "You're" because of the "re"

foreach($replace as $r) {
    $available_subjects = str_ireplace($r, '', $available_subjects);
}

And the same with this one

foreach($replace as $r) {
    $available_subjects = preg_replace('/\b'.$r.'\b/i', '', $available_subjects);
}

So I want to match the whole word, and not part of words

CodePudding user response:

First, I would replace Ticket IDs statically like you did:

$ticket_prefix = '[Ticket ID: #' . $ticket["ticketnumber"] . '] ';
$available_subjects = str_ireplace($ticket_prefix, '', $available_subjects);

Then, I would use a regular expression to replace re and fw:

$available_subjects = preg_replace('#\b(fw|re):?\s*\b#i', '', $available_subjects);
  •  Tags:  
  • php
  • Related