Trim leading white space with PHP?

后端 未结 6 1080
没有蜡笔的小新
没有蜡笔的小新 2020-12-03 19:14

There seems to be a bug in a Wordpress PHP function that leaves whitespace in front of the title of the page generated by I

相关标签:
6条回答
  • 2020-12-03 19:25

    Just to throw in some variety here: trim

     <body id="<?=trim(wp_title('', false));?>">
    
    0 讨论(0)
  • 2020-12-03 19:26

    ltrim()

    0 讨论(0)
  • 2020-12-03 19:32

    Thanks for this info! I was in the same boat in that I needed to generate page ids for CSS purposes based on the page title and the above solution worked beautifully.

    I ended up having an additional hurdle in that some pages have titles with embedded spaces, so I ended up coding this:

    <?php echo str_replace(' ','-',trim(wp_title('',false))); ?>
    
    0 讨论(0)
  • 2020-12-03 19:34

    add this to your functions.php

    add_filter('wp_title', create_function('$a, $b','return str_replace(" $b ","",$a);'), 10, 2);
    

    should work like a charm

    0 讨论(0)
  • 2020-12-03 19:37
    ltrim($str)
    
    0 讨论(0)
  • 2020-12-03 19:39
    1. Strip all whitespace from the left end of the title:

      <?php echo ltrim(wp_title('')); ?>
      
    2. Strip all whitespace from either end:

      <?php echo trim(wp_title('')); ?>
      
    3. Strip all spaces from the left end of the title:

      <?php echo ltrim(wp_title(''), ' '); ?>
      
    4. Remove the first space, even if it's not the first character:

      <?php echo str_replace(' ', '', wp_title(''), 1); ?>
      
    5. Strip only a single space (not newline, not tab) at the beginning:

      <?php echo preg_replace('/^ /', '', wp_title('')); ?>
      
    6. Strip the first character, whatever it is:

      <?php echo substr(wp_title(''), 1); ?>
      

    Update

    From the Wordpress documentation on wp_title, it appears that wp_title displays the title itself unless you pass false for the second parameter, in which case it returns it. So try:

    <?php echo trim(wp_title('', false)); ?>
    
    0 讨论(0)
提交回复
热议问题