I need to extract a certain string from a webpage and workon it. In the website it is given like this :

Decrypt the following random string: O2tsOGJeLj0saj07ODM1IQ==

I need only the base64 encoded part, but I can't think of any way. I tried using substr() and strstr() but I messed up and its giving error.

You can use preg_match(), an example:

<?php

$string = "Decrypt the following random string: O2tsOGJeLj0saj07ODM1IQ==";

preg_match('/:\s(.*)/', $string, $match);

print_r($match[1]);

The pattern /:\s(.*)/ searches the string after :, but you could also use explode():

$res = explode(':', $string);
echo trim($res[1]);

Docs:

Member Avatar for diafol

Preg is good. I found '\b' to be useful for ends.

preg_match('/:\s(.*)\b/', $string, $match);

Not tested.

Can you explain the meaning of /:\s(.*)\b/ ?

Also I would search for the base64 encoded string in source, so will it be good to search for random string: than just : ?

Member Avatar for diafol

/:\s(.*)\b/

OK the forward slashes (/) are just the delimiters for the pattern, but you could use a number of different ones, including #. So let's take those off for now:

:\s(.*)\b

The colon (:) is a literal - so search for a colon followed by a whitespace character (\s) then get all the characters (.*) up to the end of a word (word boundary) denoted by \b.

I'm flaky with my regex, so feel free to correct me.

I wouldn't use \b here as = is considered a word boundary and the == is part of the crypt. I'd use:

([^ ]*)$

Meaning the last characters of the string excluding the space. (Many ways to Rome...)

Member Avatar for diafol

Ah - good point p - didn't think of that - well, in truth, I didn't think of '=' breaking the "word". +1

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.