在PHP中指定字符后切字符串 [英] Cut string after specified character in php

查看:117
本文介绍了在PHP中指定字符后切字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这种情况下,我尝试在出现指定字符后剪切文本:

I try to cut a text after the occurence of a specified character, in this case:

"

文本示例为:

...text?" Text,

我尝试了以下操作:

$pos2 = strpos($title, '"');
if ($pos2 == true) {
             $header_title = substr($title, 0, $pos2);
    {

但是它总是削减 也是。我在$ pos2上加了数字,但一无所获。如何剪切指定的字符?

But it always cuts ", too. I messed around with adding numbers to $pos2 but couldn't figure it out. How can I cut after the specified character?

推荐答案

strpos()命令需要3个参数

1)变量

2)起始列和

3)字符数

如果只使用 substr($ title,$ pos2),您将从pos2列中的文本获取到字符串的末尾。

If you just use substr($title,$pos2) you get the text from the pos2 column to the end of the string.

<?php
$title = 'before"after';
$pos2 = strpos($title, '"');
if ($pos2 !== false) {
    $header_title = substr($title,0, $pos2+1);
} else {
    // you might want to set $header_title to something in here
    $header_title = 'ELSE';
}
echo $header_title;

结果

before"

还要测试不等于false as strpos如果找不到要搜索的字符,则返回FALSE

Also test for not equal false as strpos returns FALSE if it does not find the character you are searching for


我的本地Apache / PHP

After all the discussion below I ran it on my local Apache/PHP



<?php
$title = 'before"after';
$pos2 = strpos($title, '"');
if ($pos2 !== false) {
    $header_title = substr($title,0,$pos2+1);
} else {
    // you might want to set $header_title to something in here
    $header_title = 'ELSE';
}
?>
<!DOCTYPE html>
<html>
<head>
    <title><?php echo $header_title;?></title>
</head>
<body>

    <div> Ello Wurld</div>

</body>
</html>

产品:

这篇关于在PHP中指定字符后切字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆