Nyxynyx
Nyxynyx

Reputation: 63609

Remove first instance of substring if its infront of string

I have 2 types of strings:

String 1

<br/>Ask Me A Question<br />

                  |<br/>Search My Apartments<br/>

String 2

Ask Me A Question<br />

                  |<br/>Search My Apartments<br/>

How do I have a function that remove the first <br/> from the String 1 to get String 2, while not touching anything in String 2 if String 2 is passed into the function?

Upvotes: 0

Views: 2021

Answers (4)

Evan Davis
Evan Davis

Reputation: 36592

start your regex with ^ to match the beginning of the string.

preg_replace('/^<br\s?\/>/', '', $string)

EDIT: whoops, had an extra space (\s) in there!

EDIT 2: added an optional space back in!

Upvotes: 1

JoshStrange
JoshStrange

Reputation: 1129

@mathletics Answer is not correct for the example given in the question, This one works:

preg_replace('#^(<br/>)#iu', '', $string);

Upvotes: 0

fge
fge

Reputation: 121702

Replace `^<br/> with the empty string.

Upvotes: 0

user895378
user895378

Reputation:

If you want to avoid using a regular expression you can check if <br/> occurs at the start of the string with strpos(). If so, simply lop off the first five characters using substr()

if (strpos($string, '<br/>') === 0) {
  $string = substr($string, 5);
}

Upvotes: 0

Related Questions