strip_tags和trim无法正常工作

Jef*_* B. 0 php

我正在制作一个模因生成器,Imagick生成图像.我的问题是,即使我对用于图像的字符串执行某些操作,输出也是不正确的.

举例:

$_POST['text_top'] = " test test<br>"; //(starts with a space)
Run Code Online (Sandbox Code Playgroud)

然后我做:

$text_top = strip_tags(trim($_POST['text_top']));
Run Code Online (Sandbox Code Playgroud)

但是在$ text_top的显示上,在我将变量粘贴到图像上之后,我得到:

&nbsptest test&lt;br&gt;
Run Code Online (Sandbox Code Playgroud)

如果我从我所看到的那个调用strip_tags和trim,为什么会发生这种情况呢?

全部是UTF8编码.

谢谢!

编辑:(完整代码)

function wordWrapAnnotation(&$image, &$draw, $text, $maxWidth)
{
$words = explode(" ", $text);
$lines = array();
$i = 0;
$lineHeight = 0;
while($i < count($words) )
{
    $currentLine = $words[$i];
    if($i+1 >= count($words))
    {
        $lines[] = $currentLine;
        break;
    }
    //Check to see if we can add another word to this line
    $metrics = $image->queryFontMetrics($draw, $currentLine . ' ' . $words[$i+1]);
    while($metrics['textWidth'] <= $maxWidth)
    {
        //If so, do it and keep doing it!
        $currentLine .= ' ' . $words[++$i];
        if($i+1 >= count($words))
            break;
        $metrics = $image->queryFontMetrics($draw, $currentLine . ' ' . $words[$i+1]);
    }
    //We can't add the next word to this line, so loop to the next line
    $lines[] = $currentLine;
    $i++;
    //Finally, update line height
    if($metrics['textHeight'] > $lineHeight)
        $lineHeight = $metrics['textHeight'];
}
return array($lines, $lineHeight);
}

$text_top = strip_tags(trim($_REQUEST['text_top']));
$text_bottom = strip_tags(trim($_REQUEST['text_bottom']));
$id_base = trim($_REQUEST['id_base']);

/* Création d'un nouvel objet imagick */
$im = new Imagick($_REQUEST['image']);

/* Création d'un nouvel objet imagickdraw */
$draw = new ImagickDraw();

/* Définition de la taille du texte à 52 */
$draw->setFontSize(52);
$draw->setTextAlignment(2);
$draw->setFont("impact.ttf");
$draw->setFillColor('white');
$draw->setStrokeColor("black");
$draw->setStrokeWidth(1);

/* Ajout d'un texte */
//$draw->annotation($im->getImageWidth()/2, 50, $text);
list($lines, $lineHeight) = wordWrapAnnotation($im, $draw, stripslashes($text_top), $im->getImageWidth());
$posY= 50;
for($i = 0; $i < count($lines); $i++){
$draw->annotation($im->getImageWidth()/2, $posY + $i*$lineHeight, $lines[$i]);
}

$im->drawImage($draw);
Run Code Online (Sandbox Code Playgroud)

Sim*_*ain 5

你可以尝试一下吗?

$text_top = strip_tags(trim(html_entity_decode($_POST['text_top'], ENT_QUOTES, 'UTF-8'), "\xc2\xa0"));
Run Code Online (Sandbox Code Playgroud)

看起来你的字符串是html编码的.

编辑

添加了对UTF-8编码的支持.这样,不间断的空间被正确修剪,而不是给出一个?.

从PHP的html_entity_decode文档:

注意:

你可能想知道为什么修剪(html_entity_decode('')); 不会将字符串缩减为空字符串,这是因为''实体不是ASCII代码32(由trim()剥离),而是默认ISO 8859-1编码中的ASCII代码160(0xa0).