PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, November 20, 2022

[FIXED] How do you make preg_replace captures uppercase (php)?

 November 20, 2022     php, preg-replace, string     No comments   

Issue

I have a string: 'Some_string_to_capitalize' which I would like to transform to 'Some_String_To_Capitalize'. I have tried:

$result = preg_replace( '/(_([a-z]{1}))/' , strtoupper('$1') , $subject  )

and

$result = preg_replace( '/(_([a-z]{1}))/' , "strtoupper($1)" , $subject  )

I looked at the php man page and here on SO but found nothing. Apologies if this is a dup!

This is the equivalent SO question for Javascript.


Solution

I think you want to use preg_replace_callback:

In PHP 5.3+

<?php
$subject = 'Some_string_to_capitalize';
$result = preg_replace_callback(
    '/(_([a-z]{1}))/',
    function ($matches) {
        return strtoupper($matches[0]);
    } ,
    $subject
);

For PHP below 5.3

function toUpper($matches) {
    return strtoupper($matches[0]);
}

$result = preg_replace_callback('/(_([a-z]{1}))/', 'toUpper', $subject);


Answered By - David Stockton
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing