Adding a backslash to the end of a PHP string

时光总嘲笑我的痴心妄想 提交于 2021-02-05 09:30:30

问题


I'm attempting to do a basic query in Laravel by querying a table that holds polymorphic relationships. The table has a column called record_type which holds values such as App\MedicationError and App\PressureUlcer.

I want to run a query similar to this:

`Action::where('record_type','App\MedicationError')`

I have a set of variables containing strings like MedicationError and PressureUlcer.

How would I go about prefixing those strings with App\?

The reason I am having difficulty myself is I cannot work out how to add a backslash to the end of my 'App' string. This is what I am trying at the moment:

$type = 'App\\ '.studly_case($record->type);

But it returns App\\ RiskAssessmentUpdate. If I remove the space from the end the backslash obviously escapes the single quote. trim('App\\ ') doesn't help either.

I feel like I'm missing a really obvious (regex?) solution here. Any help would be appreciated.


回答1:


Putting two backslashes together in a single quoted string should create a single backslash, the first one escapes the second.

$type = 'App\\' . studly_case($record->type);

Alternatively, you could use a double quoted string, in the same way:

$type = "App\\" . studly_case($record->type);

My guess is that your problem lies in the studly_case($record->type) part of your code, in that it's returning a backslash at the beginning of it. Give this code a try and see if it works:

$type = "App\\" . ltrim(studly_case($record->type), '\\');

That should trim off any and all leading backslash characters.



来源:https://stackoverflow.com/questions/39327162/adding-a-backslash-to-the-end-of-a-php-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!