Samir Sheikh
Samir Sheikh

Reputation: 2401

PHP remove specific character and number from beginning of string

I want to remove brackets and number from beginning of string but problem is brackets and number is coming only specific string not all.

for example following is my string.

1) [4] Mustangs 8u
2) Pool a First Place
3) Team slect
4) [3] In pruduct

so above you can see only 1 and 4 string have number with brackets at beginning of string so i want to only remove that if that found in string.

I write following code but is not work.

<?php

foreach ($grouped as $round_number => $group) {

        $team_1_name = $group->team_1_name;
        $new_str = preg_replace('/^([0-9]* \w+ )?(.*)$/', '$2', $team_1_name);

        $date = date ('F d, Y g:iA', $unix_time);

    }

?>

Upvotes: 1

Views: 63

Answers (3)

mgutt
mgutt

Reputation: 6177

Instead regex you can use ltrim() with a character mask. If your strings never start with a number:

$new_str = ltrim($team_1_name, "0123456789[] ");

else you could check if the first char is a bracket:

$new_str = $team_1_name[0] == '[' ? ltrim($team_1_name, '0123456789[] ') : '';

Upvotes: 0

Nigel Ren
Nigel Ren

Reputation: 57131

In case your numbers are multi digit (i.e. '[11] In pruduct')...

echo preg_replace('/^(\[\d*\]?\s?)/', '$2', $team_1_name);

Upvotes: 2

Lovepreet Singh
Lovepreet Singh

Reputation: 4850

Try regular expression /^(\[[0-9]\]?\s?)/ as:

$new_str = preg_replace('/^(\[[0-9]\]?\s?)/', '$2', $team_1_name);

For reference: regexr

Upvotes: 3

Related Questions