View Full Version : return strings within a string

07-16-2008, 09:55 PM

I am having issues writing a function (i'm fairly new with programming).. I have strings like this:


How can I get return what the substrings after and including the dollar sign up to the slash?

I figured out a couple of things, like I can use substr_count to count the dollar signs, then I'd have to iterate through the string the amount of times the $ is found, but I kept getting the same result.

Any PHP pro's who could shed some light/links would be greatly appreciated.


07-16-2008, 10:09 PM
Use pattern matching, its more overhead but its easier to use. From the sounds of it, it would actually be less overhead than going through each value one by one. I'm not sure if you meant the pattern should include the / or not, so I've got both for you.

$s = 'http://www.thingy.com/$doe/$rae/$mee/';
$pattern = '/(\$.*)\//U'; // Without the last slash
$pattern = '/(\$.*\/)/U'; // With the last slash
$match = array();
preg_match_all($pattern, $s, $match);

Results are stored in $match[1], so you can count them with count($match[1]), and access each piece from the arrays in $match[1] ($match[1][0], $match[1][1], $match[1][2]...).

Sorry forgot to mention. These patterns require that the ending slash exists. To get around that, you need to set an optional for the \/ in either piece.

07-18-2008, 06:55 PM
That's awesome... worked like a charm! It ended up retaining the trailing slash with both regexes though.. I just trimmed it of though.

Thanks a lot :)

07-18-2008, 10:56 PM
You can't use both patterns as shown above. The second pattern includes the trailing slash and that pattern overwrites the original pattern. Just comment out the second $pattern = line and you should get it without the ending slashes.

07-19-2008, 01:15 PM

$string = 'http://www.thingy.com/$doe/$rae/$mee/';

$pattern = '/(\$.*)\//U';

$match = array();

preg_match_all ($pattern, $string, $match);

foreach($match[0] as $m) {echo $m . "\n";}


$doe/ $rae/ $mee/

07-19-2008, 07:49 PM
foreach ($match[1] AS $m)
echo $m . "<br />\n";

The 0 index always matches the full match given, but the pattern contains subpatterns within it (\$.*) which will be a multidimensional array at index 1.

07-21-2008, 11:32 AM
Great! thanks a lot.. I've been playing with RegexBuddy to see how these regex patterns work. Thanks for your help!