开发者

Escaping quote, both " and '

I am trying my best to work this out and it is driving me crazy, I am hoping that I can use either preg_replace or ereg_replace for this.

Basically I am putting out string of text which is taken from a news article, I am taking the first 100 characters rounded to the closest end of word, the problem occurs if a " or ' appears in the 100 characters string and no closing " or ' is present, this then causes my PHP code to fail. So I need to write some kind of replace code so that all " and ' will be replaced with \" and \' so they are escaped and don't affect my PHP.


Update

I cannot correct anything to do with database insertion as I am dealing with a very old archive of data which I cannot process and re-enter into the database so I'm stuck with what I have got there.

This is the code I have:

$text = preg_replace('/\s+?(\S+)?$/', '',substr($text, 0, 100));

echo '<开发者_开发技巧;div style="color: #8197cd;" >'.$text.'...</div>';

So that takes my text, shortens it and puts it to the nearest word.

Then I am trying to do something along the lines of:

$text = preg_replace("\"","\"",$text);
$text = preg_replace("\'","\'",$text);

But preg_replace is not a strong point of mine so that is completely wrong!


the problem occurs if a " or ' appears in the 100 characters string and no closing " or ' is present, this then causes my PHP code to fail.

You're trying to fix a problem that shouldn't be there in the first place - most likely unescaped input in a mySQL query. You need to fix that instead (it's also a security problem).

Show the code that breaks, I'm sure someone will be able to point out what needs to be done.


Something seems to be missing from your question. You should consider posting the code that is having a problem.

Having quotes inside a variable you are echoing out is not going to fail. The only thing I could imagine causing an error would be if you were using some sort of template system or code that was taking the string and using it to do an eval() somewhere, but that would be a very poor system.

If you are inserting the string into a database, then you would need to escape those characters, as mentioned by SiteSafeNL.

If an eval is the source of the problem, then htmlentities which he also suggested would fix it.

Added based on latest additions to the question

Please try this:

echo '<div style="color: #8197cd;" >'. htmlentities($text) . '...</div>';

And the preg_replaces are not useful, so simply omit that code.


Don't you need anything like mysql_real_escape_string or htmlentities?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜