so i want to have a string and then remove the text after the last of a specific characters, so
heres the string
hello world a b c this text should not be removed a b c this is the stuff that should be remove
i have tried using substr that worked but i dont knowhow to do it fo the lat fo that spcific char
my red example where i want to use this is to seperate the atributes from a string, thos are html atributes,
$data = "<xe:form data='sadasd'>"; $whatIWant = substr($data, strpos($data, " ") + 1); echo $whatIWant;
the output is data='sadasd'>
i want to remove the > at the end,i also want it to still work if its like this
<xe:form data="sadasd">
i want to remove the text after the the last double quote
Advertisement
Answer
You can use regex to capture your required text.
The regex is .*(?=a b c)
:
- The
.*
matches any character (except line breaks) 0 or more times (?=a b c)
is a positive lookahead which matches a group after the main expression without including it in the result
Regex engines are greedy by default so it should match all characters up to the last group that matches the positive lookahead.
I have created a sandbox so you can see an example and play around with it.
A code example can be seen below:
$text = "hello world a b c this text should not be removed a b c this is the stuff that should be remove"; $chars = 'a b c'; preg_match("/.*(?=$chars)/", $text, $matches); echo trim($matches[0]);
Which outputs:
hello world a b c this text should not be removed
Following on from your further examples:
$example1 = "data='sadasd'>"; $example2 = '<xe:form data="sadasd" >'; $char = '>'; preg_match("/.*(?=$char)/", $example1, $matches1); preg_match("/.*(?=$char)/", $example2, $matches2); echo trim($matches1[0]); echo trim($matches2[0]);
Which outputs:
data='sadasd' <xe:form data="sadasd"