0

How to reduce my str_replace php code ?

I want to remove aass until zass from

this is my php code, it's work good. But i want to reduce. how can i do ?

<?PHP
$str = str_replace('aass', '', $str);
$str = str_replace('bass', '', $str);
$str = str_replace('cass', '', $str);
$str = str_replace('dass', '', $str);
$str = str_replace('eass', '', $str);
$str = str_replace('fass', '', $str);
$str = str_replace('gass', '', $str);
$str = str_replace('hass', '', $str);
$str = str_replace('iass', '', $str);
$str = str_replace('jass', '', $str);
$str = str_replace('kass', '', $str);
$str = str_replace('lass', '', $str);
$str = str_replace('mass', '', $str);
$str = str_replace('nass', '', $str);
$str = str_replace('oass', '', $str);
$str = str_replace('pass', '', $str);
$str = str_replace('qass', '', $str);
$str = str_replace('rass', '', $str);
$str = str_replace('sass', '', $str);
$str = str_replace('tass', '', $str);
$str = str_replace('uass', '', $str);
$str = str_replace('vass', '', $str);
$str = str_replace('wass', '', $str);
$str = str_replace('xass', '', $str);
$str = str_replace('yass', '', $str);
$str = str_replace('zass', '', $str);
?>
  • See: http://stackoverflow.com/q/8163746 you can simply use arrays for your arguments. You could also use a regex with `preg_replace()` if you want. – Rizier123 Dec 05 '16 at 09:56

5 Answers5

7

Use a regex:

$res = preg_replace('~[a-z]ass~', '', $str);

The [a-z] character class matches any lowercase ASCII letter.

See the regex demo.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
1
<?php
    $pattern = '/[a-z]ass/';
    $replacement = '';
    echo preg_replace($pattern, $replacement, $str);
 ?>
donald123
  • 5,638
  • 3
  • 26
  • 23
0

You can use an array to search.

http://php.net/manual/en/function.str-replace.php

$search = array("aass", "bass", "cass", "dass", "eass", "fass", "gass", "hass", "iass", "jass", "kass", "lass", "mass", "nass", "oass", "pass", "qass", "rass", "sass", "tass", "uass", "vass", "wass", "xass", "yass", "zass");
$str = str_replace($search, "", $str);

Alternatively, you can see Wiktor Stribiżew's answer, as that one is even more simplified.

0

Use with Array. Like below code:

$arrayKey = array('aass', 'bass', 'cass'.....);
$arrayReplace = array('','','');
$str = str_replace($arrayKey, $arrayReplace, $str);

OR

$arrayKey = array('aass', 'bass', 'cass'.....);
    $arrayReplace = "";
    $str = str_replace($arrayKey, $arrayReplace, $str);
ujash joshi
  • 307
  • 1
  • 14
0

Use preg_replace

Example:

echo preg_replace('/([s\S]*ass)/', '', $str);

[s\S]* includes anything, numbers, letters etc