0

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?

4 Answers 4

1

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!

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for the props ... though I'm with you: When you're dealing with HTML you never know how it's going to look so you're often better off with a regex that allows for all the possibilities. Of course, DOM parsing is also your friend in such matters :)
Your regex does not work for the example given in the question
It's worth noting that the space character should be optional \s?
Notice the "\s" there is no space in the example so it doesn't match. @mathletics fixed it and it works now
@JoshStrange rdlowrey is right, considering that it's mixed in this example (I realize the first has no space but if dealing with input from, say, a CMS, who knows how it's actually going to shake out.)
|
0

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);
}

3 Comments

Ha! Good answer. Sometimes you don't need regex!
Make sure you use the triple-equals (===) in case your version of php's strpos returns false (which will match 0 but won't === 0)
@Tim Yes, it's probably worth pointing that out. IF you're asking such a question you probably aren't fully aware of the difference between double equals and triple equals.
0

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

Comments

0

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

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

1 Comment

fixed mine; had an extra space character because I looked at the second break.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.