0

I'm looking to filter numbers from a string, and make them bigger in one case, and hide them in the other. The best way, as I understood, would be to use a custom function via functions.php and probably Javascript. The string is using a unique div class.

Here's how it looks in HTML:

<div class="big-numbers">15th Amendment</div>

what I think would be a good result to work with in CSS later on:

<div class="big-numbers"><span>15</span>th Amendment</div>

I previously used a code to filter the first word, but I cannot use it here due to ordinal numbers, and not sure how can I filter just numbers.

2
  • the string you want to parse comes from an editor ? Commented Aug 30, 2024 at 0:50
  • it's ACF field, but it shouldn't matter right? Commented Aug 31, 2024 at 13:58

1 Answer 1

0

You could use PHP's preg_replace() to wrap all the numbers (ie, any successive combination of 0 through 9) in a <span> tag.

add_filter( 'the_content', 'wpse426625_number_wrapper' );
/**
 * Wraps any number in the content in a <span> tag.
 *
 * @param  string $content The post content.
 * @return string          The content with the numbers wrapped in <span>s.
 */
function wpse426625_number_wrapper( $content ) {
    $content = preg_replace(
        '/(\d+)/', // \d is any digit; + matches one or more.
        '<span class="numbers">$1</span>', // $1 is the text inside () in the search.
        $content
    );
    return $content;
}

This assumes you want to wrap all the numbers in WordPress's post content in <span> tags; I've also added a class to the spans so you can target them with CSS. If my assumptions are incorrect, I recommend you edit your question to clarify what you're looking for.

Also note: this question is really a PHP question (or possibly a Javascript question), not a WordPress question. I've answered it here, but it more properly belongs on Stack Overflow.

Regular expressions (such as those used by preg_replace()) are very powerful; if you haven't encountered them before, you'd do well to look into how they work.

2
  • and performance wise this is better than JS? Anyway, if I would like to wrap numbers in specific div class, would preg_replace also work? Commented Aug 31, 2024 at 13:58
  • 1. It happens on the server side, not the client, so the performance hit happens when the page is generated rather than on your users' computers. 2. The 2nd parameter to preg_replace() can be pretty much whatever you want, so yes, you should be able to wrap the numbers in <div> tags or anything else you'd like. Commented Sep 1, 2024 at 1:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.