skip to Main Content

could you please tell me the way to get the first letter of two words that are linked with a specific character. For instance: hello_world I want to convert it to h_w

I tried to get the first letter of the two words. But I don’t know the way to keep the underscore between them

$str = 'hellow_world';
echo preg_replace("/(w)[^_]*?(?:_|$)/", "$1", $str);

2

Answers


  1. Replace the following with nothing:

    (?:b|_)[a-z]   # Find a word boundary or an underscore followed by a letter,
    K              # forfeit both of them,
    [a-z]*          # then match 0 or more letters.
    

    Try it on regex101.com.

    Alternatively, you can match the whole word and replace it with the first letter using $1:

    (?<=b|_)       # Match something preceded by a word boundary or an underscore
    ([a-z])[a-z]*   # that is 1 or more letters, the first of which we capture.
    

    Try it on regex101.com.

    Login or Signup to reply.
  2. If you want to keep only the first character of a word not being an underscore, you can use B to assert a non word boundary not preceded by _ and match 1+ word chars other than _

    Note that w can also match _ which you can exclude with a negated character class [^W_]

    B(?<!_)[^W_]+
    

    See a regex demo.


    If the words must have at least one _ where there is a word character before and after the underscore, you can make use of the G anchor and 2 capture groups.

    (?:b([^W_])[^W_]*|G(?!^))(_[^W_])[^W_]*
    

    The pattern matches:

    • (?: Non capture group for the alternatives
      • b([^W_]) A word boundary, capture a single word char other than _ in group 1
      • [^W_]* Match optional word chars other than _
      • | Or
      • G(?!^) Assert the current postion at the end of the previous match, not at the start
    • ) Close the non capture group
    • (_[^W_]) Capture _ and a single word char other than _ in group 2
    • [^W_]* Match optional word chars other than _

    See a regex demo and a PHP demo

    $regex = '/(?:b([^W_])[^W_]*|G(?!^))(_[^W_])[^W_]*/m';
    $str = 'hello_world
    this_is_a_test_string
    
    ab_bc_cd
    a_b_c
    a_bb_c
    a_b_cc
    aa_b_c
    
    this_is_
    this_
    this
    Hi there';
    $subst = "$1$2";
    
    echo preg_replace($regex, "$1$2", $str);
    

    Output

    h_w
    t_i_a_t_s
    
    a_b_c
    a_b_c
    a_b_c
    a_b_c
    a_b_c
    
    t_i_
    this_
    this
    Hi there
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search