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

PhpStorm自定义Live Template:将逗号分隔字符串转为关联数组

Fixing PhpStorm Live Template for Comma-Separated Strings to Associative Array

Got it, let's tweak your Live Template so it can handle comma-separated strings and spit out clean associative array entries. Here's a step-by-step solution:

Step 1: Open Live Templates Settings

  • Go to File > Settings (or press Ctrl+Alt+S on Windows/Linux, Cmd+, on Mac)
  • Navigate to Editor > Live Templates
  • Either select the existing PHP group (or create a new custom group for your templates)
  • Click the + button and choose Live Template

Step 2: Configure the Template

Fill in these details:

  • Abbreviation: Pick something memorable, like keyval (you'll type this to trigger the template)
  • Template Text: Just put $RESULT$ (we'll handle the transformation via the variable expression)
  • Description: Optional, but helpful—e.g., "Convert comma-separated string to associative array key-value pairs"

Step 3: Define the RESULT Variable

Click the Edit Variables button next to the template text. For the RESULT variable:

  • In the Expression field, paste this Groovy script:
    com.intellij.openapi.util.text.StringUtil.split(SELECTION, ",").collect { "'${it.trim()}' => ${it.trim()}," }.join("\n")
    
  • Check the Skip if defined box so PhpStorm doesn't prompt you for input
  • Click OK to save the variable setup

Step 4: Set Applicable Contexts

Click the Define button below the template text, then check PHP (you can narrow it down to specific PHP contexts like "PHP code" if needed). Click OK to confirm.

Step 5: Test It Out

  • Select a comma-separated string, e.g., $entity_type,$user_id,$post_title
  • Press your template abbreviation (keyval) followed by the expansion key (default is Tab)
  • You'll get clean, formatted associative array entries:
    '$entity_type' => $entity_type,
    '$user_id' => $user_id,
    '$post_title' => $post_title,
    

Optional Tweaks

  • If you prefer all entries on a single line, replace "\n" in the expression with ", "
  • If you don't want the trailing comma, adjust the collect function to "'${it.trim()}' => ${it.trim()}" and add a comma between entries in the join: join(", ")

内容的提问来源于stack exchange,提问作者Protomancer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 10:23:47