Cut string after specified character in php

后端 未结 2 640
独厮守ぢ
独厮守ぢ 2021-01-27 06:52

I try to cut a text after the occurence of a specified character, in this case:

The text example is:

...text?“ Text,
         


        
相关标签:
2条回答
  • 2021-01-27 06:54

    The strpos() command requires 3 parameters

    1) The Variable

    2) The start column and

    3) the numbers of characters

    If you just use substr($title,$pos2) you get the text from the pos2 column to the end of the string.

    <?php
    $title = 'before“after';
    $pos2 = strpos($title, '“');
    if ($pos2 !== false) {
        $header_title = substr($title,0, $pos2+1);
    } else {
        // you might want to set $header_title to something in here
        $header_title = 'ELSE';
    }
    echo $header_title;
    

    RESULT

    before“
    

    Also test for not equal false as strpos returns FALSE if it does not find the character you are searching for

    After all the discussion below I ran it on my local Apache/PHP

    <?php
    $title = 'before“after';
    $pos2 = strpos($title, '“');
    if ($pos2 !== false) {
        $header_title = substr($title,0,$pos2+1);
    } else {
        // you might want to set $header_title to something in here
        $header_title = 'ELSE';
    }
    ?>
    <!DOCTYPE html>
    <html>
    <head>
        <title><?php echo $header_title;?></title>
    </head>
    <body>
    
        <div> Ello Wurld</div>
    
    </body>
    </html>
    

    Produces:

    0 讨论(0)
  • 2021-01-27 07:09

    I think this can be helpful for anyone :

    $title = 'sometext?"othertext';
    $pos2 = strpos($title, '"');
    
    $title = substr($title, 0, $pos2+1);
    
    echo $title;
    

    Output:

    sometext?"


    If you want the text after the " mark:

    $title = 'sometext?"othertext';
    $pos2 = strpos($title, '"');
    
    $title = substr($title, $pos2+1);
    
    echo $title;
    

    Output:

    othertext

    0 讨论(0)
提交回复
热议问题