I have a custom field that contains a sentence along with a punctuation mark at the end. I am looking to use this field as a title of the article on my homepage, but in doing so I would like to remove the last character of that custom field (so that the ending period of the sentence is not included in the title).

Here is the code I use to display the custom field on my homepage:

<?php echo get_post_meta($post->ID, one_line_summary, true); ?>

I'm not great with PHP programming, so specific examples with my code would be preferred. Thanks in advance!


This is more of a PHP question then a WordPress question.

If you want to remove punctuation marks like (.,-;:) you can try this recursive version:

$s = get_post_meta( $post->ID, 'one_line_summary', TRUE );

if( function_exists( 'remove_punctuation_marks' ) )
    $s = remove_punctuation_marks( $s );


 * Remove punctuation marks (.,-;:) if they're the last characters in the string
 * WPSE: 119519
 * @param string $s
 * @return string $s
function remove_punctuation_marks( $s )
    $remove = array( '.', ',', '-', ';', ':' );          // Edit this to your needs 
    if( in_array( mb_substr( $s, -1 ), $remove, TRUE ) )
        $s = remove_punctuation_marks( mb_substr( $s, 0, -1 ) ); 

    return $s;    

where you can define $remove to your needs and mb_substr() is a multi-byte version of substr().


The following test:

echo  remove_punctuation_marks( '...Hello world...:,;' );

gives the output:

...Hello world


It's better to use rtrim() as @toscho pointed out ;-)

Then in your case:

$s = get_post_meta( $post->ID, 'one_line_summary', TRUE ); 
$s = rtrim( $s, '.,;:' );

where you can add to the list (.,;:) of punctuation marks to remove.

  • 1
    You couldn’t find rtrim()? :) – fuxia Oct 21 '13 at 5:15
  • ...not the first time reinventing the wheel happens or the last time, in my case, thanks ;-) – birgire Oct 21 '13 at 8:22
  • Sorry I do not know anything about rtrim() any way you could give me an example of how to do it my get_post_meta example inside a loop in Wordpress? – Dustin J Oct 21 '13 at 18:49
  • sure, please check out the updated answer. – birgire Oct 21 '13 at 18:58
  • It worked using your help from above, full line is here: <?php $s = get_post_meta( $post->ID, 'one_line_summary', TRUE ); $s = rtrim( $s, '.,;:!?' ); echo $s ?> – Dustin J Oct 21 '13 at 22:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.