...

View Full Version : Grabbing random text out of a string..



cyphix
02-12-2006, 09:51 PM
Hey guys.... was wondering if anyone had any ideas for this one.... say we had this text for example..



<some code>random text</some code>


Now..... say I knew what came BEFORE and AFTER the "random text" part; how would I go about pulling out the random text?

Thanks for any help! :)

Element
02-12-2006, 09:55 PM
Not sure what you mean but:



<?php

$str = 'Some text in this variable';
$parts = explode(' ', $str);
echo array_rand($parts);

?>

missing-score
02-12-2006, 11:32 PM
Maybe something like this:



<?php

$string = '<some code>random text here</some code>';

$match = '/\<some code\>(.+?)\<\/some code\>/is';
$randomText = preg_replace( $match, "$1", $string );

?>

cyphix
02-13-2006, 09:34 AM
Thanks guys.... yeah; was thinking about how to do it after I posted this & figured that using preg_replace() would probably be the best way to go about doing it. :)

Missing-score..... can you tell me what the "$1" parameter is? :confused:

Thanks!

Mhtml
02-13-2006, 09:42 AM
$1 will give the contents of the pattern matched by (.+?)

missing-score
02-13-2006, 11:21 AM
For every bracket set you use in a regular expression (eg: (.+?), ([a-z0-9]+)), you can access the contents of that specific section with a number. In that case, the first (and only) bracket group was retrieved using $1.

cyphix
02-13-2006, 12:16 PM
Oh ok... thx! :)

What about these parts..



$match = '/\<some code\>(.+?)\<\/some code\>/is';


I didn't think ">" needed to be escaped? Thought it was only.. "[ . \ * ? +" (except in some cases such as class expressions) and "- ^ $" in some circumstances.

Doesn't using "\<" anchor the next RE to the start of a word & "\>" anchor the previous RE to the end of a word?" :confused:

Oh & what does "is" mean at the end there? I know that "i" makes it case-insensitive; but not sure what the added "s" does?

Thanks!

missing-score
02-13-2006, 12:18 PM
It depends what delimiter you use I believe. You can use more than / to start a regex pattern. To be honest, my regex is moderatley limited, Ive only ever really worked with the / delimiter.

cyphix
02-13-2006, 12:21 PM
Oh ok.... thanks! :) Btw... I edited my post slightly after you posted I believe..

missing-score
02-13-2006, 12:23 PM
This page may help you understand the modifiers:

http://uk2.php.net/manual/en/reference.pcre.pattern.modifiers.php

cyphix
02-13-2006, 12:44 PM
Alright.. TY! :)

missing-score
02-13-2006, 12:45 PM
Alright.. TY! :)
No problem, feel free to ask any other questions you may have :)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum