1

So far I managed to isolate and count pictures in a string by doing this:

preg_match_all('#<img([^<]+)>#', $string, $temp_img); 
$count=count($temp_img[1]);

I would like to do something similar with parts that would look like this:

"code=mYrAnd0mc0dE123".

For instance, let's say I have this string:

$string="my first code is code=aZeRtY and my second one is code=qSdF1E"

I would like to store "aZeRtY" and "qSdF1E" in an array.

I tried a bunch of regex to isolate the "code=..." but none has worked for me. Obviously, regex is beyond me.

2
  • 2
    Could you please explain what you mean by I would like to do something similar with parts that would look like this "code=mYrAnd0mc0dE123". Commented Jul 11, 2013 at 14:47
  • Of course: I meant detecting every occurrence of "code=aBcD" that appears in a string (where aBcD could be anything alphanumerical), and stock the values in a variable like "$temp_code[1]" for instance. Just like I did with the images. I edited the question accordingly. Commented Jul 11, 2013 at 14:51

2 Answers 2

4

Are you looking for this?

preg_match_all('#code=([A-Za-z0-9]+)#', $string, $results);
$count = count($results[1]);
Sign up to request clarification or add additional context in comments.

1 Comment

Simple enough, I was expecting something tricker. Thank you very much.
1

This:

$string = '
    code=jhb2345jhbv2345ljhb2435
    code=jhb2345jhbv2345ljhb2435
    code=jhb2345jhbv2345ljhb2435
    code=jhb2345jhbv2345ljhb2435
    ';

preg_match_all('/(?<=code=)[a-zA-Z0-9]+/', $string, $matches);

echo('<pre>');
print_r($matches);
echo('</pre>');

Outputs:

Array
(
    [0] => Array
        (
            [0] => jhb2345jhbv2345ljhb2435
            [1] => jhb2345jhbv2345ljhb2435
            [2] => jhb2345jhbv2345ljhb2435
            [3] => jhb2345jhbv2345ljhb2435
        )
)

However without a suffixing delimiter, it won't work correctly if this pattern is concatenated, eg: code=jhb2345jhbv2345ljhb2435code=jhb2345jhbv2345ljhb2435

But perhaps that won't be a problem for you.

1 Comment

No, it shouldn't be a problem as there will be spaces between codes. My point is to allow a user to simply add something like "youtube=AzErTy24" in his post to automatically instantiate and format the player accordingly. The only risk is having any punctuation at the end but as youtube doesn't use punctuation in its ID's, it will be easy to detect and remove them if any.

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.