dongyili5843 2018-08-16 10:58
浏览 15
已采纳

传入php函数的字符串在字符串中的第一个空格后断开

I've created a simple function that outputs an image with the correct html markup, seen below. The problem I am facing is when I pass into the alt text that has a space in it, such as "My cat is great", the alt breaks and shows alt="My" like <img src="blah.jpg" alt="My" cat is great class="home">. I'm having a hard time trying to figure this out. Any thoughts?

function image_creator($image_url, $alt=false, $class=false) {
    $string = '<img src='.$image_url.' alt='.$alt.' class='.$class.'>';
    return $string;
}
  • 写回答

4条回答 默认 最新

  • duangan1945 2018-08-16 11:03
    关注

    A little user failure. No problem!

    Make sure you have your <img> tag correctly.

    $image_url = 'https://example.com/image';
    $alt       = 'My cat is awesome';
    $class     = 'image';
    

    So:

    function image_creator($image_url, $alt=false, $class=false) {
        $string = '<img src='.$image_url.' alt='.$alt.' class='.$class.'>';
        return $string;
    }
    

    Outcome:

    <img src="https://example.com/image" alt="My" cat="" is="" awesome="" class="image">

    Should be:

    function image_creator($image_url, $alt=false, $class=false) {
        $string = '<img src="'.$image_url.'" alt="'.$alt.'" class="'.$class.'">';
        return $string;
    }
    

    Outcome:

    <img src="https://example.com/image" alt="My cat is awesome" class="image">

    Do you see the differences? Look carefully at the quotes.

    Documentation:

    Some examples about using quotes:


    Personally I would like to use:

    // $image below is being sent to the function
    $image = [
        'image_url' => 'https://example.com/image',
        'alt'       => 'My cat is awesome',
        'class'     => 'image',
    ];
    
    function image_creator($image = [])
    {
        if(empty($image))
        {
            return 'No image';
        }
    
        return '<img src="' . $image['image_url'] . '" alt="' . $image['alt'] . '" class="' . $image['class'] . '">';
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度