开发者

PHP and Regex if word found

开发者 https://www.devze.com 2023-02-23 13:11 出处:网络
I\'m looking to only perform a strip of characters if a certain word is found in a string, so if the开发者_JAVA百科 word numbers is matched with regex it will perform a strip all actual numbers 0-9 or

I'm looking to only perform a strip of characters if a certain word is found in a string, so if the开发者_JAVA百科 word numbers is matched with regex it will perform a strip all actual numbers 0-9 or preg replace them to nothing, BTW The numbers will always be wrapped in "". What would be the best way to put these two functions together? An example would be if the data was Man, Numbers are fun! "123ABC" it would return Man, Numbers are fun! "ABC" If numbers isn't present they are ignored.


I feel like some of the answers here are overcomplicated. Maybe it's just me, but this should be all you need:

if (stripos($str, 'numbers') !== false) {
    $str = preg_replace('/\d/', '', $str);
}

EDIT: If you only want numbers that are inside quotation marks, you might be able to do it with a regex, but I'd definitely do it this way:

if (stripos($str, 'numbers') !== false) {
    $arr = explode('"', $str);

    for ($i = 1; $i < count($arr); $i += 2) {
        $arr[$i] = preg_replace('/\d/', '', $arr[$i]);
    }

    $str = implode('"', $arr);
}


If I understand the question correctly, maybe something like:

if (strpos($string, "numbers") !== false) {
    $string = preg_replace('/"\d+"/', '', $string);
}


Something like this should work for you:

$str = 'Man, Numbers are fun! "123ABC"';
var_dump(preg_replace_callback("(.*\bNumbers\b.*)",
create_function(
'$matches',
'return preg_replace("/(\"[^\d]*)\d+(.*\")/", "$1$2", $matches[0]);'
),
$str));

OUTPUT:
string(27) "Man, Numbers are fun! "ABC""

\bNumbers\b will make sure to match word Numbers with word boundaries so that xyzNumbers and Numbersxyz are NOT matched.


You could use the strpos function to check for the string in the first place.

Something like

if(strpos($mystr,"Some value")!==false) { /*preg_replace here.*/ }


@Ryan Cooper: Try --

$input = 'Man, Numbers are fun! "123ABC"';

echo stripnums("Numbers", $input);

function stripnums($needle, $haystack)
{
    if (stripos($haystack, $needle) !== 0)
    {
        return preg_replace('/[0-9]/', '', $haystack);
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消