Wizard
Wizard

Reputation: 11285

Remove all before specific symbol in string PHP

For example i have string one two three four five and I want remove all characters before two and after four , I know that is function preg_replace() but I don't know how to write this expression, I not know what does mean for example '/([a-z])([A-Z])/' please say what is name of this expression in $pattern and what they mean

Upvotes: 1

Views: 2793

Answers (2)

anubhava
anubhava

Reputation: 785611

In case you're looking for preg_replace based solution then here it is:

$str = 'one two three four five';
var_dump ( preg_replace('#^.*?(two.*?four).*$#i', '$1', $str) );

Expanation: RegEx used in preg_replace first matches text upto your starting text two then matches upto your end text four and finally replaces it with matched string thus discarding all text before two and all text after four. Please note .*? makes your matching non-greedy. Read more about regex here: http://www.regular-expressions.info/

OUTPUT

string(14) "two three four"

Upvotes: 2

Matt Fellows
Matt Fellows

Reputation: 6532

preg_replace is a function which takes in regular expressions to do replacements.

You can and should learn about these, as they are very powerful, but they aren't essential for your problem.

You can use strpos and substr functions

substr takes a string that you want to shorten, a start location and a number of characters and returns the shortened string.

strpos takes a string that you want to search, and a string that you want to search for and returns the location of the second string in the first.

So you can use them as such:

$text = "one two three four five";
$locationOfTwo = strpos($text, "two"); //The location in the string of the substring "two" (in this case it's 4)
$locationOfFour =strpos($text, "four") + strlen("four"); //Added the length of the word to get to the end of it (In this case it will set the variable to 18).
$subString = subsstr($text, locationOfTwo, (locationOfFour-locationOfTwo));

Upvotes: 1

Related Questions