Page 1 of 1

unable to do a simple regex :(

Posted: Wed Dec 19, 2007 1:39 am
by claws
problem:

Code: Select all

//I have a multiline string. lets say.
$str = <<<EOS
php
is a
great
serverside
language
EOS;

echo '<input type="button" onlick=javascript:function("'.$str.'"); />';
since the $str is a multiline string. in javascript as expected the error comes unterminated string literal

for this i have to relpace all multiline charachers so that the javascript function parameter string should look like.

Code: Select all

"php"+
"is a"+
"great"+
"serverlide"+
"language"
for that i am using the following line in php

Code: Select all

preg_replace('/\n/',' "+\n" ',$str);
or
preg_replace('/\n/',' ',$str);
or
preg_replace('/\s/','  ',$str);
neither of these are working :(

i tried '\r' , '\r\n' also instead of \n but no use any help

Posted: Wed Dec 19, 2007 6:42 am
by stereofrog
Actually, that expression works just fine.
More general approach would be something like

Code: Select all

# make string safe to use in javascript
function js_escape($str) {
	return strtr($str, array(
		"\r" => "\\r", "\n" => "\\n", "\t" => "\\t", 
		"\"" => "\\x22", "'" => "\\x27", "\\" => "\\x5c"));
}

# example

$str = js_escape($str);
echo "<a href='' onclick='alert(\"$str\")'>test</a>";