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

SOQL中转义&符号问题:Salesforce搜索含&字符字符串报错

Fixing SOSL Search for Strings Containing Ampersands (&) in Salesforce

Hey there! I see you're running into an issue searching for a campaign name with an ampersand in Salesforce using SOSL. Let's break down why this happens and how to fix it.

Why the Error Occurs

The & character is a special operator in SOSL (it acts as the logical AND operator). When you include it directly in your search string without proper escaping, Salesforce tries to parse it as an operator instead of treating it as a literal character—hence the mismatched character '&' expecting '}' error.

Your attempts with htmlentities (converting & to &) didn't work because SOSL doesn't recognize HTML entities; it would just search for the literal string & instead of the actual &. Generic preg_replace without targeting SOSL-specific special characters also won't address the root problem.

The Solution: Escape SOSL Special Characters

To search for literal special characters in SOSL, you need to escape them with a backslash (\). Here are two ways to apply this to your code:

Option 1: Manual Escape for the Ampersand

If you know the exact string you're searching for, you can directly escape the &:

$campaign_name = 'A \& B Campaign'; // Escape & with a backslash
$search = 'FIND {'.$campaign_name.'} IN NAME FIELDS RETURNING CAMPAIGN(ID)';
$searchResult = $mySforceConnection->search($search);
var_dump('$searchResult: ' . print_r($searchResult, true));

Option 2: Dynamic Escape for All SOSL Special Characters

For a robust solution (especially if your search string comes from user input or dynamic data), create a function to escape all SOSL special characters. These include: \, {, }, (, ), |, &, !, [, ], ^, ~, *, ?, :

// Helper function to escape SOSL special characters
function escapeSosl($string) {
    $specialChars = ['\\', '{', '}', '(', ')', '|', '&', '!', '[', ']', '^', '~', '*', '?', ':'];
    foreach ($specialChars as $char) {
        $string = str_replace($char, '\\' . $char, $string);
    }
    return $string;
}

// Usage in your code
$campaign_name = 'A & B Campaign';
$escapedCampaignName = escapeSosl($campaign_name);
$search = 'FIND {'.$escapedCampaignName.'} IN NAME FIELDS RETURNING CAMPAIGN(ID)';
$searchResult = $mySforceConnection->search($search);
var_dump('$searchResult: ' . print_r($searchResult, true));

How This Works

By prefixing each special character with a backslash, you're telling Salesforce to treat the character as a literal part of your search string—not as an operator or syntax element. This resolves the parsing error and ensures your search looks for the exact campaign name you intend.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 06:38:26