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

Sunday, November 20, 2022

[FIXED] How to lowercase a specific word in a string php

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

Issue

Hye Guys !!

I need your help ! Here are 2 elements:

$string = "Legend Of Zelda";
$array = array("to","of","at");

I'd like to check if $string contains one of the $array elements and lowercase it. Tried this, but failed ... i got the felling that the first element of the preg_replace should be a pattern or so ?

echo preg_replace($array, mb_strtolower($array), $string);

Any idea ? Thanks a lot from France !


Solution

Use preg_replace_callback:

$string = "Legend Of Zelda";
$array = array("to","of","at");
echo preg_replace_callback('~\b(?:' . implode("|", $array) . ')\b~ui', function ($m) {
    return mb_strtolower($m[0]);
  }, $string);

See PHP demo.

The regex will look like \b(?:to|of|at)\b here, see its demo online.

The /i flag will ensure case insensitive search and /u will handle all Unicode chars correctly.



Answered By - Wiktor Stribiżew
Answer Checked By - Pedro (PHPFixing Volunteer)
  • 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