Find a substring and replace it to a specified cha

2019-08-18 10:54发布

问题:

I got a string, built up like the following:

$string = 'HUB_NENNWERT_KATALOG:[0 TO 4.9],GREIFKRAFT_OEFFNEN_KATALOG:[2000 TO 5999],WERKSTUECKGEWICHT:[0 TO 14.9]';

The ints in this String can be different. So what I want is, check if a certain field is in the String, i.e. 'HUB_NENNWERT_KATALOG'. If returned true, I want to delete the whole substring inclusive the comma. So it would return a new String like this:

$string = 'GREIFKRAFT_OEFFNEN_KATALOG:[2000 TO 5999],WERKSTUECKGEWICHT:[0 TO 14.9]';

I know alle fields, that can occur, but not the values. How do I achieve this?

Hope it was described clear enough.

回答1:

You could try:

if(preg_match("/HUB_NENNWERT_KATALOG:\[.*\]/isU",$string){
    preg_replace("/HUB_NENNWERT_KATALOG:\[.*\]/isU","", $string);
}


回答2:

You can use regular expression and replace the string found with empty string. Please look at this function:

preg_replace

Good luck!



回答3:

If the structure of the string is always the same, maybe this could be another approach:

$filters = array('HUB_NENNWERT_KATALOG', 'HUB_ISTWERT_KATALOG');
$filtered = array();

$string = 'HUB_NENNWERT_KATALOG:[0 TO 4.9],GREIFKRAFT_OEFFNEN_KATALOG:[2000 TO 5999],WERKSTUECKGEWICHT:[0 TO 14.9]';

$checks = explode(',',$string);
foreach($checks as $check) {
    $a = explode(':',$check);
    if(!in_array($a[0],$filters)) {
      $filtered [] = $check;
    }
}

$filtered_string = implode(',', $filtered);