php:: apply backticks to first word in sentence
Posted
by
Hailwood
on Stack Overflow
See other posts from Stack Overflow
or by Hailwood
Published on 2011-01-14T00:43:04Z
Indexed on
2011/01/14
0:54 UTC
Read the original article
Hit count: 142
Hi guys,
basically what I am trying to do is,
I have an array that looks something like this:
array(
array(
'select' =>'first string',
'escape' => true
),
array(
'select' =>'second',
'escape' => true
),
array(
'select' =>'the third string',
'escape' => true
),
array(
'select' =>'fourth string',
'escape' => false
),
)
I am looping over it and I want to end up with this output
array(
array(
'select' =>'`first` string',
'escape' => true
),
array(
'select' =>'`second`',
'escape' => true
),
array(
'select' =>'`the` third string',
'escape' => true
),
array(
'select' =>'fourth string',
'escape' => false
),
)
so basic rules are
- backticks are only applied if escape is true
- backticks are only applied to the first word in a sentence
- if there is only one word backticks are applied to the word
My plan was to use
if($item['escape']) {
$pos = (strpos($item['select'], ' ') === false ? strlen($item['select']) : strpos($item['select'], ' '));
$item['select'] = '`' . substr($item['select'], 0, $pos) . '`' . substr($item['select'], $pos, strlen($item['select']));
}
but the $item['select'] =
line seems rather long winded, is there a better way to write it?
© Stack Overflow or respective owner