I want to remove any words in the text of posts, before a specific letter (such as :) that comes at the beginning of the text and add that word to the end of the text.
for example:
» Original text
Franky: This is a test.
» content after change
This is a test.
Quote from: Franky
I want to remove any words in the text of posts, before a specific letter (such as :) that comes at the beginning of the text and add that word to the end of the text.
for example:
» Original text
Franky: This is a test.
» content after change
This is a test.
Quote from: Franky
Share
Improve this question
asked Sep 3, 2019 at 7:27
user168547user168547
52 bronze badges
1
- Can you please mark this as the answer if this answered your question? – Ted Stresen-Reuter Commented Sep 4, 2019 at 11:03
1 Answer
Reset to default 1Given this post_content: "Franky: This is a test."
When the post is displayed
Then the post_content is displayed as:
"This is a test.
Quote from: Franky"
There are many, many ways you could do this. I think the best would be to run it through a filter on the_content
but for sake of simplicity in this example, imaging you have the following where you would normally see the_content()
in a WordPress template file.
$search_pattern = '@^([^:]+):\s*(.*)$@';
$replace_pattern = '$2<br>' . "\n" . 'Quote: $1';
$new_post_content = preg_replace( $search_pattern, $replace_pattern, get_the_content() );
echo $new_post_content;
The reason you should run this through a WordPress filter is that there may be other filters acting on the_content()
that also modify it (or that will need to modify it after your filter).
Also, the exact regular expression will need to be tweaked. I gave an example that assumes that the input is all on one line. If you have multiline input, you'll need to adjust accordingly. How to write regular expressions, however, is another subject so if you need help with that, I would post a separate question.
And finally, to add this to the_content filter, it would be something like this:
add_filter( 'the_content', function( $input ) {
$search_pattern = '@^([^:]+):\s*(.*)$@';
$replace_pattern = '$2<br>' . "\n" . 'Quote: $1';
return preg_replace( $search_pattern, $replace_pattern, $input );
}, 10, 2);
And… If you want this modification to support localization, you'll need to run 'Quote from:' through the WordPress translation functions, but that too is a separate question.
Good luck!