Remove changing substrings from string

Hi is there anyway to check a string for any instances of something like this
“(3)” where the number “3” could be any integer. So basically I want to search a string for any instances of a integer in brackets “(integer)” and remove it.

So my string was something like

[php]$string = “String (2) string string string (7)”

function($string)[/php]

output would be “String string string string”

where there integers in brackets could be any number

A good place to start would be to look at regular expressions. These allow you to define patterns and then search for them or replace them inside of a string.

Regular expressions can get very complicated, so I’ll provide a working one for you then try to explain it. Saying this, it would be much better for you to look at them and have a go at learning some yourself as they are an invaluable skill for a (PHP) programmer.

The expression is:

/\([0-9]\)/

The two / symbols start and end the expression.

The \ symbol escapes the round bracket (removing its meaning in the regular expression). This means it gets taken into account as a round bracket, not as what a round bracket means inside of a regular expression.

The [ ] (square brackets) define a set of characters we’re looking for.

The 0-9 says, look for numbers from zero to nine.

To use this, we will use the preg_replace function in PHP. It accepts three arguments:

  • The regular expression
  • What to replace matches of the regular expression with
  • The string that we are dealing with

[php]$string = “String (2) string string string (7)”;
$string = preg_replace(’/([0-9])/’, ‘’, $string);
echo($string);[/php]

This produces the output of:

String string string string

Have a look at:
www (dot) regular-expressions (dot) info/quickstart.html

For more information.

Sponsor our Newsletter | Privacy Policy | Terms of Service