PHP 字符串格式问题


PHP string formatting issue

我正在使用工具提示jquery插件,它需要在链接属性中使用单引号,如下所示:

   <a href="#" class="tooltip" title="<img src='my-image.png' width='100' height='100' />

但是我正在尝试将其保存在PHP变量中,如下所示:

$calendar.= '<div class="event-day tooltip"><a href="event.php?id='.$event['event_id'].'"title="<img src="my-image.jpg" width="500" height="400"/><span class="hb">'.$hour.'</span> '.$event['name'].'</a></div>';

正如您在标题属性中看到的那样,由于 title=,它不起作用">

你说你需要生成这个:

<a href="#" class="tooltip" title="<img src='my-image.png' width='100' height='100' />

。但这从一开始就是完全无效的 HTML。

我怀疑您实际上想插入一些任意 HTML,例如:

 <img src='my-image.png' width='100' height='100' />

。在标题属性内:

 <a href="#" class="tooltip" title="">Foo</a>

这不是特别困难:

<?php
$title = "<img src='my-image.png' width='100' height='100' />";
echo '<a href="#" class="tooltip" title="' . htmlspecialchars($title) . '">Foo</a>';
<a href="#" class="tooltip" title="&lt;img src='my-image.png' width='100' height='100' /&gt;">Foo</a>

使用转义字符''

$calendar.= '<div class="event-day tooltip"><a href="event.php?id='.$event['event_id'].'"title="<img src=''my-image.jpg'' width=''500'' height=''400''/><span class="hb">'.$hour.'</span> '.$event['name'].'</a></div>';

使用 ''

   $calendar.= '<div class="event-day tooltip"><a href="event.php?id='.$event['event_id'].'"title="<img src=''my-image.jpg'' width=''500'' height=''400''" /><span class="hb">'.$hour.'</span> '.$event['name'].'</a></div>';
缺少在

title="之前添加空格

<a href="event.php?id='.$event['event_id'].'" title="<img src="my-image.jpg" width="500" height="400"/><span class="hb">'.$hour.'</span> '.$event['name'].'</a>';
                                           ^^^^^^               

问题是 2 个属性hreftitle混合在代码中。 你需要分开它。

尝试将其保存在转义引号的变量中,而不是在标题属性中使用双引号。

此外,您的标记不正确,因为您正在关闭从未打开的<a><div>。(在下面的示例中更改了它(

$calendar.= '<div class="event-day tooltip"><a href="event.php?id='.$event['event_id'].'"title="<img src=''my-image.jpg'' width=''500'' height=''400''/><span class=''hb''>'.$hour.'</span> '.$event['name'].'">';

将图像标记存储在变量中,并按如下方式使用它:

$myImg="<img src='my-image.jpg' width='500' height='400'/>";
$calendar.= "<div class='event-day tooltip'><a href='event.php?id=$event[event_id]' title='$myImg'><span class='hb'>$hour</span>$event[name]</a></div>";

另外,在与字符串一起使用时,您不需要连接 PHP 变量。

echo "Hi $myname, how u doing?";

优于

echo "Hi ".$myname.", how u doing?";

试试这个:

$calendar = '<div class="event-day tooltip"><a href="event.php?id='.$event['event_id'].' "title="<img src=''my-image.jpg'' width="500" height="400"/><span class="hb">'.$hour.'</span> '.$event['name'].'</a></div>';