Search code examples
phpwordpresscustom-fieldscodex

Extract number values from string in WordPress custom field


Inside WordPress, every post has a single custom field with this kind of "value":

HTML:5, JQUERY: 20, PHP:38

This value is different in every post, not only for numbers, but also for names. I mean that other post could have:

CSS:90, HTML5: 32, LINUX: 80, ETHERNET: 22

Considered this, I want to extract and print every name (for example HTML) and the number of that name (for example 5).

Sometimes it could happen that a number is part of the name (ex: HTML5), so I think that the only way would be to recognize string before and after ":", considering that the last one won't have "," at the end.

I'm conscious it would be much easier to have more custom fields, one per "name" like HTML:5 and other one called JQUERY with value 20, but it would be really long.


Solution

  • This will probably work just as well as anything else.

        $string= 'CSS:90, HTML5: 32, LINUX: 80, ETHERNET: 22';
    
        $ar=explode(",",$string);
    
        foreach($ar as $item){
           $v= explode(":",$item);
           $array[]= array( 'key'=> $v[0], 'text'=> $v[1]  ); // or print html etc....
    
        }
    
        var_dump($array);