Cludas18
Cludas18

Reputation: 55

PHP select word after a certain word

Hello everyone I'm working on something where I'm going to take a person's ID from a string, which is after that person's name. So how it works, is a POST value is stored in a variable. In this case, $user = "Himatochi". I want to select the users ID (its a SteamID, if that matters) which comes right after their name in a string. But it should be noted that there are more than 1 players and ID's listed in the string.

So right now here's the string I have

hostname: Development Server version : 14.09.08/24 5914 secure udp/ip : 192.168.1.4:27015 (public ip: 135.120.128.85) map : gm_flatgrass at: 0 x, 0 y, 0 z players : 2 (16 max) # userid name uniqueid connected ping loss state adr # 2 "Chalu87" STEAM_0:1:70377242 05:01 35 0 active 192.168.1.4:27006 # 4 "Himatochi" STEAM_0:0:53654842 01:13 267 0 active 105.20.142.139:27005

So I basically want code that tells PHP to store the SteamID after $user into a new variable.

Upvotes: 0

Views: 344

Answers (2)

Dan Sherman
Dan Sherman

Reputation: 23

If the format is consistent, you can get away with just using string functions, and that should be faster than envoking the complexity of the regex engine. You should run a quick benchmark to be sure though.

<?php
$str = 'hostname: Development Server version : 14.09.08/24 5914 secure udp/ip : 192.168.1.4:27015 (public ip: 135.120.128.85) map : gm_flatgrass at: 0 x, 0 y, 0 z players : 2 (16 max) # userid name uniqueid connected ping loss state adr # 2 "Chalu87" STEAM_0:1:70377242 05:01 35 0 active 192.168.1.4:27006 # 4 "Himatochi" STEAM_0:0:53654842 01:13 267 0 active 105.20.142.139:27005';

$user = 'Himatochi';

$user = '"' . $user . '"';
$str = substr(strrchr($str, $user), 2);
$userId = substr($str, 0, strpos($str, " "));

echo $userId;

Upvotes: 0

chris85
chris85

Reputation: 23892

You could use a regex to accomplish this, assuming the data structure is consistent and $user is always set.

<?php
$user = 'Himatochi';
$data = 'hostname: Development Server version : 14.09.08/24 5914 secure udp/ip : 192.168.1.4:27015 (public ip: 135.120.128.85) map : gm_flatgrass at: 0 x, 0 y, 0 z players : 2 (16 max) # userid name uniqueid connected ping loss state adr # 2 "Chalu87" STEAM_0:1:70377242 05:01 35 0 active 192.168.1.4:27006 # 4 "Himatochi" STEAM_0:0:53654842 01:13 267 0 active 105.20.142.139:27005';
preg_match('~"' . preg_quote($user) . '"\s+(.*?)\s~', $data, $userid);
echo $userid[1];

Output:

STEAM_0:0:53654842

This searches for " username (with any special regex characters escaped) " then at least one white space. After the whitespace it captures everything until the next whitespace. The next whitespace character seemed like the easiest thing to match the end of the userid with.

Upvotes: 3

Related Questions