2

If I had a string of text e.g:

<p>Hello world here is the latest news ##news?123## or click here to read more</p>

I want to look through the string and find anything starting with ##news? Then I want to save that and the id 123 and trailing hashes as a variable, so the final output would be:

$myvar == "##news?123##"

How can I use PHP to read that input string and save that specific part as a variable?

0

2 Answers 2

3

preg_match is your friend for this sort of problem.

        $str='<p>Hello world here is the latest news ##news?123## or click here to read more';
        $pttn='@(##news\?(\d+)##)@';
        preg_match( $pttn, $str, $matches );

        $myvar=$matches[0];
        $id=$matches[2];

        echo $myvar.' '.$id;
Sign up to request clarification or add additional context in comments.

1 Comment

I think your pattern is probably better than mine :)
2

Assuming you're not trying to parse HTML but as you say, just find any occurrence starting with "##news?" then you can use regex happily here:

$string = '<p>Hello world here is the latest news ##news?123## or click here to read more';
$matches = array();
preg_match_all("/(##news\?.*?)\s/",$string,$matches);
print_r($matches);

Comments

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.