James Ambardnishvili
James Ambardnishvili

Reputation: 43

How to check if character is part of a word

I've searched around here about this topic, suggestions that i saw are from topics like

Check if a character is a word boundary

but i don't know if that's what i need exactly

My problem is this, I have to extract a string from word which can be a single character but also can be multiple, in this question I'm only discussing single character because that's the main problem in my situation, other types where string is multiple characters is easily identifiable because there's only one encounter for it in the string where I'm removing it from

"S Shoulder Pads"

In this example i have to remove character S from this string, problem is data is not really consistent, So strpos() or strrpos() don't always work. this same string can be provided reversed and because of this i can't consistently know where my needed character is located at

"Shoulder Pads S"

My only validation for the single character string that i need to extract is, if character is a single letter and it's not a part of any word in this example S then it's valid for removal. is there some nice way of doing this in PHP?

Upvotes: 0

Views: 124

Answers (1)

nice_dev
nice_dev

Reputation: 17805

As you have guessed it correctly, you can use a word boundary \b around your string to match it in such a way that it exists individually and not as a part of any string. You can use preg_replace to replace the matched string with any string, which is the second parameter for this function.

Snippet:

<?php

$tests = [
        "S Shoulder Pads",
        "Shoulder Pads S",
        "SSSSS S S S"
    ];

foreach($tests as $test){
    echo preg_replace('/\bS\b/','',$test),PHP_EOL;
}

Upvotes: 2

Related Questions