首页 \ 问答 \ 更有效地运行3 str_replace(Run 3 str_replace more efficiently)

更有效地运行3 str_replace(Run 3 str_replace more efficiently)

所以我目前运行以下代码:

$current_link = get_author_posts_url($user_id,strtolower($user_info->user_login));
$current_link = str_replace(" ", "-", $current_link);
$current_link = str_replace(".-", "-", $current_link);
$current_link = str_replace("author", "authors", $current_link);

但是我觉得这段代码可能更有效率。 因为我在同一个字符串上运行str_replace 3次。 所以我使用preg_replace来最小化代码,如下所示:

$cLPatterns = array(' ', '.-');
$current_link = preg_replace($cLPatterns, '-', $current_link);
$current_link = str_replace("author", "authors", $current_link);

但有没有办法使用str_replace("author", "authors", $current_link)作为preg_replace一部分

如何使此代码最有效。

干杯


So I currently run the following code:

$current_link = get_author_posts_url($user_id,strtolower($user_info->user_login));
$current_link = str_replace(" ", "-", $current_link);
$current_link = str_replace(".-", "-", $current_link);
$current_link = str_replace("author", "authors", $current_link);

However I feel that this code could be more efficient. As I'm running str_replace 3 times on the same string. So I used preg_replace to minimize the code like so:

$cLPatterns = array(' ', '.-');
$current_link = preg_replace($cLPatterns, '-', $current_link);
$current_link = str_replace("author", "authors", $current_link);

But is there a way to use the str_replace("author", "authors", $current_link) as part of preg_replace

How can I make this code the most efficient.

Cheers


原文:https://stackoverflow.com/questions/44533491
更新时间:2022-01-31 10:01

最满意答案

听起来你正在寻找分页。 这与你的服务器有关,而不是你的客户端。

实现分页的典型方法是让服务器接受偏移量并限制集合资源的参数。

例如,假设你的服务器上有一些你可以检索的项目

GET myapi/items

您可以引入偏移量和限制查询参数,以指定您要收集哪个页面。

GET myapi/items?offset=50&limit=25

然后,您将相应地编程您的API客户端以使用这些值。

你可以在服务器上推出你自己的分页机制,或者你可以使用符合你所使用的语言和/或框架的东西,这可能是更好的方式去做这件事(最好不要重新发明轮子) 。 例如,我使用Spring,所以使用spring-data的分页功能。

这段视频对于从53:00开始的分页有相当好的解释

https://www.youtube.com/watch?v=hdSrT4yjS1g


It sounds like you're looking for pagination. This has more to do with your server than your client.

A typical way to implement pagination, is to have your server accept offset and limit parameters for a collection resource.

So for example, say you had a collection of items on your server that you could retrieve with

GET myapi/items

You would introduce the offset and limit query parameters to specify which page you wanted out of your collection.

GET myapi/items?offset=50&limit=25

Then you would program your API client accordingly to make use of the values.

You can roll your own paging mechanism on the server, or you can use something that fits with the language and / or framework you're using, which is probably a better way to go about this (best not to re-invent the wheel). For example, I'm using Spring, so use the paging features of spring-data.

This video has a fairly good explanation of paging starting at 53:00

https://www.youtube.com/watch?v=hdSrT4yjS1g

相关问答

更多