Jump to content

Replacing&extracting an item in a string


Shadowing

Recommended Posts

well crap lol. i dont think i can turn this into a function that i can use for more then one thing.

cause i cant fill in the name variable when telling it when passing the 3rd agrument

lol hard to explain, anyone get what im saying? i knew the problem would exist before writing but wrote it for an example

 

$_POST['message'] = "hey whats up @baal how are you doing. @paul bleh";

echo str_exchange(" @",$_POST['message']," <a href='' class='profile_name' id='$name'>$name</a>");	

function str_exchange($item,$string,$replace) {	

    $count = substr_count($string, $item); 
    $x = 0;

While($x < $count) {

	preg_match('/\s@([^\s]+)\s/', $string, $matches);	

		$name = $matches[1];

                        //$replace = " <a href='' class='profile_name' id='$name'>$name</a>";

		$string = str_replace(" ".trim($matches[0]), $replace, $string);
	++$x;
}

return $string;
}

Link to comment
Share on other sites

idk guys im pretty confused lol.

 

this is giving me a undefine function error cant figure that one out

i dont understand the $1 in the links

 

 

$_POST['message'] = "hey whats up @baal how are you doing. @paul bleh";

echo str_exchange(" @",$_POST['message']," <a href='' class='profile_name' id='$1'>$1</a>");	

function str_exchange($item,$string,$replace) {	

	$count = substr_count($string, $item); 
	$x = 0;

While($x < $count) {

		$string = preg_replace("/\\s@(\\S+)/u", $string, $replace);

	++$x;
}

return $string;
}

Link to comment
Share on other sites

Shadowing: All you need is the code I posted above, the last two lines to be accurate.

Just replace "$string" in the "preg_replace ()" call with $_POST['message'] and you're set.

 

As for the "$1" in the links, they're variables for "preg_replace ()" to insert the results of the capturing sub groups. Where the number is the same index you'd get if you'd use "preg_match_all ()"

 

PS: You wouldn't happen to have all of this code wrapped in a function, would you?

function test () {
    echo test2 ();
    function test2 () { return 2; }
}
test ();
PHP Fatal error:  Call to undefined function test2() in php shell code on line 2

Link to comment
Share on other sites

preg_replace only replaces one occurance right? or am I wrong about that

cause i need it to do replace on multiple ones

thats why i made the loop

 

If i dont need the loop then i guess i wouldnt need a function

 

$_POST['message'] = "hey whats up @baal how are you doing. @paul bleh";

Link to comment
Share on other sites

I get a return of

hey whats upbaal how are you doing.paul bleh

 

no links

cause the html return is

hey whats upbaal<a href="" class="profile_name" id=""><\/a> how are you doing.paul<a href="" class="profile_name" id=""><\/a> bleh<\/li>

 

it doesnt fill in the variables

 

$_POST['message'] = "hey whats up @baal how are you doing. @paul bleh";

$replace = '$1<a href="" class="profile_name" id="$2">$2</a>';

$_POST['message'] = preg_replace("/\\s@(\\S+)/u", $replace, $_POST['message']);	
echo $_POST['message'];

Link to comment
Share on other sites

You seem to have taken the replacement string from the right post, but the actual RegExp from the wrong.

Here's the correct version:

$_POST['message'] = "hey whats up @baal how are you doing. @paul bleh";

// Replace user references with links to profiles.
$replace = '$1<a href="profile.php?name=$2" class="profile_name" id="$2">$2</a>';
echo preg_replace ("/((?<!\\S))@(\\S+)/u", $replace, htmlspecialchars ($_POST['message']));

Added "htmlspecialchars ()" for security's sake, to prevent XSS and CSRF.

Link to comment
Share on other sites

wow nice working now.

 

ive never seen variable replacement like that.

 

I really need to learn regex

 

my game is completly ajaxed no need for href="profile.php?name=$2" im using class for the trigger and id for the data

when i started ajax though didnt think about using the href attribute though to store data.

 

cause really i should be doing href='$1' instead of having a attribute just sitting there not being used.

 

Thanks alot to everyone who replied to this thread.

Thanks for showing me that ChristinanF

 

 

so if i get this right $1 is the rest of the string and $2 is the replacement just like selecting the key 0 or 1 from an array or what ever

 

 

Link to comment
Share on other sites

Last question first, because I'm weird like that. :P

so if i get this right $1 is the rest of the string and $2 is the replacement just like selecting the key 0 or 1 from an array or what ever

Not quite, the $1 refers to the first matching sub group. In other words, the first pair of "clean" parentheses. In this case it's the character immediately preceding the @. Namely the beginning of the string or a whitespace character. Index "0" doesn't exists for replacement variables within RegExps.

The rest of the string is unmatched by the RegExp, and as such is not affected by it.

 

ive never seen variable replacement like that.

 

I really need to learn regex

Variable replacement in RegExp can be quite useful, indeed. As for learning RegExp, I recommend RegExp.info.

 

my game is completly ajaxed no need for href="profile.php?name=$2" im using class for the trigger and id for the data

when i started ajax though didnt think about using the href attribute though to store data.

I consider it courteous, and a matter of professional pride, to write a site so that it'll be completely functionally working even without JS. ;)

 

Thanks for showing me that ChristinanF

You're welcome, glad I could help. :)

 

PS: Fixed my name. :P

Link to comment
Share on other sites

sorry that i keep draging this thread on lol

 

but is it possible to wrap a function around these variable replacements

tried this it didnt work

 

 

"$1<a href='' class='profile_name' id='$2'>".ucfirst($2)."</a>"

 

Link to comment
Share on other sites

I meant like everything is ajaxed. no webpages ever flip. zero headers in Stargate System Lords http://www.stargatesystemlords.com/

 

 

but later on i thought about making a mobile non javascript, then if i did use href i wouldnt have to change anything then it would just work either way. So i guess its probably a good idea i didnt use href for data storing so i can later go back and use the href for token storing for the links

Link to comment
Share on other sites

oh crap lol i need help with one more regex :P

 

I need to etxact ~planet name~ I have to put it on both sides since the name can have a space in it

but i also dont need a space before it like i did with " @name"

 

but watching your guy's example im thinking something like

 

 

"/~(\\~+)/u"

 

but i would need it to get rid of the 2nd ~ also

 

is the u getting rid of the first ~?

 

 

 

 

 

Link to comment
Share on other sites

That RegExp is looking for a single tilde (~), followed by a single backslash (which doesn't have any effect, btw) and then one or more tildes. With the following tildes being stored in a sub group. Not quite what you're looking for, in other words.

If you formalize (like I did above) the pattern rule you want to match, then you should find it a lot easier to translate it into RegExp.

 

The "u" modifier is to make the RegExp UTF-8 compatible. You can read more about the different modifiers in the PHP manual.

Link to comment
Share on other sites

This works on the first expression "/\s+@(.*?)\s/"

instead of "/((?<!\\S))@(\\S+)/u"

does the same thing

but with using only one variable

 

preg_replace("/\s+@(.*?)\s/", " <a href='' class='profile_name' id='$1'>$1</a> ", $_POST['message']);

 

got this expression to work for second expression "/~(.*?)~/"

Link to comment
Share on other sites

No, those two RegExps are not the same. One is looking for something that's preceded by one or more spaces, while the other is looking for everything that's not preceded by a character1 that is not a white space2. The one I posted includes support for sentences that start with @name, while the other does not.

This means the sentence "@Christian is testing" would not get matched.

 

Your second expression, however, is quite correct. :)

 

1The lack of any character satisfies this requirement, even if it can sound a bit convoluted.

2Yeah, I know. Double negatives suck in natural languages, but for RegExp they work quite nicely. As long as you can wrap your head around them...

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.