Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
84 views
in Technique[技术] by (71.8m points)

php - remove the characters after the last of a specific character

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
question from:https://stackoverflow.com/questions/66049346/remove-the-characters-after-the-last-of-a-specific-character

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use regex to capture your required text.

The regex is .*(?=a b c):

  1. The .* matches any character (except line breaks) 0 or more times
  2. (?=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"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...