You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

  1. Split the input string: Use spaces to break the original string into a list of individual words.
  2. Check for keyword matches: Loop through each word to see if it contains your target keyword.
  3. 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.
  4. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 07:58:27