PHP - add underscores before capital letters

前端 未结 5 2271
梦如初夏
梦如初夏 2021-02-18 14:48

How can I replace a set of words that look like:

SomeText

to

Some_Text

?

5条回答
  •  无人及你
    2021-02-18 15:22

    $s1 = "ThisIsATest";
    $s2 = preg_replace("/(?<=[a-zA-Z])(?=[A-Z])/", "_", $s1);
    
    echo $s2;  //  "This_Is_A_Test"
    

    Explanation:

    The regex uses two look-around assertions (one look-behind and one look-ahead) to find spots in the string where an underscore should be inserted.

    (?<=[a-zA-Z])   # a position that is preceded by an ASCII letter
    (?=[A-Z])       # a position that is followed by an uppercase ASCII letter
    

    The first assertion makes sure that no underscore is inserted at the start of the string.

提交回复
热议问题