jkque/laravel-string-replace

用于解决混乱的 str_replace 的辅助工具

1.0.0 2020-07-05 03:59 UTC

This package is auto-updated.

Last update: 2024-09-13 10:45:51 UTC


README

Latest Version on Packagist Total Downloads

当您遇到str_replace变得有些复杂的情况时,此包将帮助您。

简介

当您看到类似这种情况时

$remove_characters = ['<p>', '</p>', '&#39;', '&#039;', '<h2>', '</h2>', '<strong>', '</strong>', '&nbsp;', '&#63;','@name', '&rsquot;', '&quot;', '@firstname'];
$replace_with = ['', '', "'", "'", '', '', '', '', '', '?', $user->name, "'", '"', $user->first_name];

$message = str_replace($remove_characters, $replace_with, $message);

更简洁的方式

use Jkque\StringReplace\StringReplace;

$message = StringReplace::content($string)
    ->when($user, function ($string) use($user) {
        return $string->with(new UserStringReplace($user));
    })
    ->variables([
        '&#39;' => "'",
        '&#63;' => '?'
    ])
    ->replace();
use Jkque\StringReplace\StringReplace;

use App\User;

class UserStringReplace extends StringReplace
{
    public function __construct(User $user)
    {
        $this->variables([
            '@name' => $user->name,
        ]);
    }
}

用法

use Jkque\StringReplace\StringReplace;

$string = 'We are awesome <p>in php</p> replacethis';

$string = StringReplace::content($string)
    ->variables([
        'replacethis' => 'coding',
    ])
    ->replace(); // the ending method to be called

您可以使用条件闭包 whenunless

$string->when($somecondtion, function ($string) {
 // do something;
})

默认情况下会移除 HTML 标签,但您可以通过在 stripTags(false) 方法中传递 false 值来关闭此功能。

管道

为了将复杂的过程分解成单独的任务,您可以创建一个扩展 Jkque\StringReplace\StringReplace 的类。

use Jkque\StringReplace\StringReplace;

class RemoveBadWords extends StringReplace
{
    public function __construct()
    {
        $this->variables([
            'badword' => '*',
        ]);
    }
}

创建此类的辅助命令为 php artisan string-replace:pipe {name} {model? : With model}。您可以在配置文件中更改模型命名空间,默认为 'App\'。

安装

您可以通过 composer 安装此包

composer require jkque/laravel-string-replace

发布配置文件

php artisan vendor:publish --provider="Jkque\StringReplace\StringReplaceServiceProvider"

测试

composer test

变更日志

请参阅 CHANGELOG 了解最近更改的详细信息。

贡献

请参阅 CONTRIBUTING 了解详情。

安全

如果您发现任何与安全相关的问题,请通过电子邮件 johnkevin.cadungog@gmail.com 联系,而不是使用问题跟踪器。

致谢

许可

MIT 许可证 (MIT)。有关更多信息,请参阅 许可文件