PHP开发需求:按空格分割字符,提取含指定关键词的完整单词
Solution: Extract the Full Word Containing Your Target Keyword
Got it, let's work through this problem. The core task is to split a string by spaces, find the complete word that includes your specified keyword, and return only that word (ignoring everything before and after it).
Step-by-Step Breakdown
- Split the input string: Use spaces to break the original string into a list of individual words.
- Check for keyword matches: Loop through each word to see if it contains your target keyword.
- Return the matching word: As soon as you find a word that includes the keyword, return it—this automatically discards all content before and after the word.
- Handle edge cases: Optionally, return an empty string or custom message if no matching word exists.
Python Code Implementation
Here's a straightforward function that does exactly what you need:
def extract_target_word(input_str, keyword): # Split the string into a list of words using spaces words = input_str.split() # Iterate through each word to find the one with the keyword for word in words: if keyword in word: return word # Return empty string if no matching word is found (adjust as needed) return ""
Test Your Examples
Let's validate with the cases you provided:
- Input:
"Hello holy world", Keyword:"ho"→ Output:holy - Input:
"Hello holy world", Keyword:"hol"→ Output:holy - Input:
"testing text", Keyword:"tex"→ Output:text
Bonus: Handle Multiple Matching Words
If your input has multiple words containing the keyword (e.g., "holy holiday hello" with keyword "ho"), you can modify the function to return all matches as a list:
def extract_all_target_words(input_str, keyword): words = input_str.split() return [word for word in words if keyword in word]
For the example above, this would return ["holy", "holiday"].
内容的提问来源于stack exchange,提问作者Kubaxus Kolek
相关产品推荐
相关产品推荐

