Find a substring and replace it to a specified cha

2019-08-18 11:12发布

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.

3条回答
Juvenile、少年°
2楼-- · 2019-08-18 11:36

You could try:

if(preg_match("/HUB_NENNWERT_KATALOG:\[.*\]/isU",$string){
    preg_replace("/HUB_NENNWERT_KATALOG:\[.*\]/isU","", $string);
}
查看更多
爷的心禁止访问
3楼-- · 2019-08-18 11:42

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

preg_replace

Good luck!

查看更多
Animai°情兽
4楼-- · 2019-08-18 11:48

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);
查看更多
登录 后发表回答