简体   繁体   中英

Regex/PHP Remove everything before first letter

I need to remove all characters before the first letter... How do I search for the position of the first occurance of [az] & [AZ].

$test = "1234 123423-34 This is a test";

$string = preg_replace('/REGEX/', "", $test);
echo $string;

Should output: This is a test

Use a negated character class with a leading anchor.

^[^A-Za-z]+

Regex Demo: https://regex101.com/r/149aDt/1

PHP Demo: https://3v4l.org/7m6RZ

$test = "1234 123423-34 This is a test";
echo preg_replace('/^[^A-Za-z]+/', '', $test);

You can try this:

<?php
$test = "1234 123423-34 This is a test";
for($i=0;$i<strlen($test);$i++){
    if(!ctype_alpha($test[$i])){
        $test[$i] = '';
    }else{
        break;
    }
}
echo $test;

In addition to chris85 answer, if you want to deal with unicode characters:

$str = '123 μεγάλο τριχωτό της γάτας';
$result = preg_replace('~\PL+~Au', '', $str); 

You can use strcspn function to return the length of the initial string segment which does NOT matching any of the given characters, eg:

$position = strcspn($test, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");

This does not account for Unicode letters.

Also note that you can accomplish your task (replacement) with regular expressions, without the need to determine this position (see the other answer).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM