Naourass Derouichi
Naourass Derouichi

Reputation: 793

Remove string's portion from the start until certain word

I have a string :

$s = "I am not foo+bar";

I want to remove the first portion of $s starting from the beginning of the string until the word "foo+" so it becomes "I am not foo+bar" :

$s == "bar"

How can I achieve that with PHP?

Edit : I have a "+" sign inside the string. Why preg_replace is not replacing it? The pattern that I've used is /^(.*?\bfoo+)\b/. Any ideas?

Upvotes: 0

Views: 82

Answers (1)

chris85
chris85

Reputation: 23892

You should be able to use a regex to find everything up until a certain word. For your example,

/^(.*?\bfoo)\b/

Should work with preg_replace.
The ^ makes sure we start at the beginning of the string.
.*? is anything (excluding new lines add the s modifier to allow new lines as well) until the first foo.

Simply put: \b allows you to perform a "whole words only" search using a regular expression in the form of \bword\b. A "word character" is a character that can be used to form words. All characters that are not "word characters" are "non-word characters".

-http://www.regular-expressions.info/wordboundaries.html

Regex demo: https://regex101.com/r/gJ3nS7/3

Rough untested replacement example using preg_quote.

preg_replace('/^(.*?\b' . preg_quote('foo', '/') . '\b/', '', $s);

Longer example the + is a special character but also is a non-word character so the \b won't work trailing that. You can put the + into an optional grouping with the word boundary and that should work.

https://regex101.com/r/gJ3nS7/5

/^(.*?\bfoo(?:\+|\b))/

Upvotes: 2

Related Questions